skip to Main Content

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.

Here is result:
enter image description here

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.

2

Answers


  1. this works for me. please add required attribute to input
    <input type="file" name="file" required>

    and replace echo $_FILES; //get notice error to echo '<pre>'.print_r($_FILES, true).'</pre>';

    result:

    Array
    (
        [file] => Array
            (
                [name] => 314370969_1174754369788841_1709138246209437707_n.jpg
                [type] => image/jpeg
                [tmp_name] => C:xampp_newtmpphp6BBB.tmp
                [error] => 0
                [size] => 275646
            )
    
    )
    uploads/
    314370969_1174754369788841_1709138246209437707_n.jpg
    uploads/314370969_1174754369788841_1709138246209437707_n.jpg
    jpg
    The file 314370969_1174754369788841_1709138246209437707_n.jpg has been uploaded successfully.
    

    and pleease check the post_max_size and upload_max_filesize value in php.ini because the defult value is 2MB

    Login or Signup to reply.
  2. If you’re having trouble uploading photos via PHP’s move_uploaded_file function, there are a few potential causes to check for:

    Permissions: Check that the directory where you’re trying to move the uploaded file to has the correct permissions. It should be writable by the user that PHP is running as (usually the web server user).

    File size limits: PHP has several settings that can limit the size of uploaded files. Check the upload_max_filesize and post_max_size settings in your php.ini file and adjust them as needed.

    Form enctype: Make sure that the form that’s being used to upload the file has the enctype attribute set to "multipart/form-data". Without this, the file data won’t be properly encoded and won’t be able to be uploaded.

    File name: Make sure that the file name doesn’t contain any invalid characters (such as slashes) that could interfere with the file path when trying to move it. You can use PHP’s basename function to extract just the filename part of the path.

    Destination path: Check that the destination path you’re trying to move the file to is correct and exists. You can use PHP’s is_dir function to check if the directory exists and mkdir to create it if it doesn’t.

    Error messages: Check for any error messages that may be generated during the upload process. You can use PHP’s $_FILES[‘file’][‘error’] variable to check for errors. Possible error codes include UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, and UPLOAD_ERR_EXTENSION.

    By checking these potential causes and making any necessary adjustments, you should be able to resolve the issue and successfully upload your photos via PHP’s move_uploaded_file function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search