I read a lot of threads here about move_uploaded_file() here, but I cannot find the answer. Im trying code from this website - https://www.simplilearn.com/tutorials/php-tutorial/image-upload-in-php but it doesnt work.
I have 3 files: dbConfig.php
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "****";
$dbPassword = "****";
$dbName = "image_test";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
main.php
<!DOCTYPE HTML>
<html>
<head>
<title>#tyvlasystudio</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select Image File to Upload:
<input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
upload.php
<?php
// Include the database configuration file
include 'dbConfig.php';
$statusMsg = '';
echo $_FILES;
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
echo $targetDir ."<br>";
echo $fileName ."<br>";
echo $targetFilePath ."<br>";
echo $fileType ."<br>";
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
// Display status message
echo $statusMsg;
?>
But it doesnt worked.
I dont know what is bad in this code. Thanks for your advice
Edit 16.2.2023 - 23:00 I figured it out, that problem maybe will be in POST metod. Ive tried now easy code with two files:
main1.php
<html>
<body>
<form method="post" action="main2.php">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>
main2.php
<?php
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
?>
But only with GET method I'll get right answer.