Php upload image to directory

Php upload image to directory

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Your PHP Image Upload Returns "Invalid File"

The code snippet you are looking at is a classic example of how file upload handling was taught in early web development tutorials, but it contains several critical flaws that prevent it from functioning as intended in modern environments. Specifically, the logic checks for MIME types using $_FILES["file"]["type"], which is notoriously unreliable, and then immediately re-evaluates the extension without properly normalizing the data.

When you run this script and receive "Invalid file," it is almost certainly because the MIME type check fails first, or the case sensitivity of the extension comparison causes a mismatch. Browsers often report MIME types with specific capitalization (e.g., image/png) while your $allowedExts array contains lowercase strings (png). Furthermore, relying on $_FILES["file"]["type"] is dangerous because users can modify their user agents or upload tools to send arbitrary MIME types.

To fix this, you must rely exclusively on the file extension and perform strict validation against a whitelist of allowed extensions. The standard practice involves extracting the extension from the filename, converting it to lowercase to ensure case-insensitive comparison, and verifying that the resulting string exists in your $allowedExts array.

Here is a robust implementation that addresses the specific issues in your original script:

<?php
// Define the destination directory
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$upload_ok = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
} else {
    // Validate extension against whitelist
    $allowed_extensions = ["jpg", "jpeg", "gif", "png"];

    if (in_array($imageFileType, $allowed_extensions) && $_FILES["file"]["error"] == 0) {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "The file ". htmlspecialchars(basename($_FILES["file"]["name"])). " has been uploaded successfully.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    } else {
        echo "Sorry, only JPG, JPEG, GIF & PNG files are allowed to be uploaded.";
    }
}
?>

Notice the use of basename() and pathinfo(). These functions help isolate the filename and its extension without needing to manipulate the raw string with explode, which is error-prone if the user includes query parameters in the filename (e.g., image.jpg?ver=1.0). The move_uploaded_file() function is also preferred over manually copying files from the temp directory because it handles temporary file cleanup and provides better security guarantees.

Security should not be an afterthought. If you are maintaining a legacy application or migrating from older frameworks, ensure that your server's php.ini settings allow uploads in the directory where your script resides by configuring upload_max_filesize and post_max_size. Additionally, always sanitize file inputs to prevent path traversal attacks. Never trust the filename provided by the user; always generate a new, unique name using uniqid() or a hash function before saving the file to avoid collisions and potential overwriting of existing assets.

For projects requiring more robust handling of file uploads, including progress bars, chunked uploads, and automated validation, frameworks like Laravel provide dedicated services. The underlying logic remains similar—validate the extension, check the MIME type using finfo_file() for server-side verification, and ensure the destination directory has the correct permissions—but the abstraction layer handles much of the complexity.

If you are building a new application or need to integrate file handling into an existing Laravel project, the official documentation at https://laravelcompany.com provides detailed guides on managing uploads with their storage driver, which abstracts away the raw PHP file I/O operations and offers better scalability out of the box.

Our network