skip to Main Content

I’m currently working on a file upload feature for my PHP application, and I’m encountering a problem with the move_uploaded_file function. Here’s a simplified version of my code:

<?php
$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);

if (move_uploaded_files($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
    echo "File uploaded successfully!";
} else {
    echo "Error uploading file.";
}
?>

Despite having the correct permissions set for the "uploads" directory, the file doesn’t seem to be moved there. I’ve checked the $_FILES array, and it contains the expected information. What could be causing this issue, and how can I troubleshoot and resolve it?

Additional Information:

  • I’m using PHP 7.4.
  • The "uploads" directory has the necessary write permissions.
  • I’m testing this on a local development server.

Any help or insights would be greatly appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    I have found another code

    <?php
    $targetDirectory = "uploads/";
    
    // Check if the form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Check if there was no error during file upload
        if ($_FILES["fileToUpload"]["error"] == UPLOAD_ERR_OK) {
            $targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
    
            // Check if the file is of the expected type and size
            $allowedTypes = ["jpg", "jpeg", "png", "gif"]; // Add more if needed
            $fileExtension = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    
            if (in_array($fileExtension, $allowedTypes) && $_FILES["fileToUpload"]["size"] <= 5000000) { // Adjust size limit as needed
                if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
                    echo "File uploaded successfully!";
                } else {
                    echo "Error uploading file.";
                }
            } else {
                echo "Invalid file type or size.";
            }
        } else {
            echo "Error during file upload: " . $_FILES["fileToUpload"]["error"];
        }
    }
    ?>
    

  2. There is a small typo in your code. The function name should be move_uploaded_file (singular "file"), not move_uploaded_files (plural "files"). Here’s the corrected code:

    <?php
    $targetDirectory = "uploads/";
    $targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
    
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "File uploaded successfully!";
    } else {
        echo "Error uploading file.";
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search