PHP Validating the File Upload

PHP Validating the File Upload

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

Stefan Bogdanescu

Founder & Senior Architect

The Trap of Trusting $_FILES['type'] in PHP File Validation

When building a file upload handler, the most common misconception is assuming that $_FILES['type'] is reliable. As you likely discovered, this superglobal returns the MIME type declared by the client application. If a user uploads an image and renames it from .gif to .jpg, the server sees image/jpeg because the browser correctly identified the file content before the transfer. However, if a user attempts to trick your script by renaming a malicious executable named shell.exe to photo.jpg, some clients might still send application/octet-stream or even claim it is an image depending on the headers they send.

Relying solely on $_FILES['type'] is dangerous because it trusts the client. A savvy attacker can craft requests that bypass these checks entirely. The standard validation pattern often seen in tutorials involves checking both the declared MIME type and the file extension:

$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));

if (
    (($_FILES['file']['type'] == "image/gif") ||
     ($_FILES['file']['type'] == "image/jpeg") ||
     ($_FILES['file']['type'] == "image/jpg") ||
     ($_FILES['file']['type'] == "image/png")) &&
    ($_FILES['file']['size'] < 20000) &&
    in_array($extension, $allowedExts)
) {
    // Proceed with upload
}

This code checks the extension twice in a way that looks redundant but serves a specific purpose. The first check against $_FILES['type'] validates the MIME type sent by the client. The second check via in_array($extension, $allowedExts) ensures the filename ends with an allowed suffix. While checking both seems thorough, it still relies on user input: the filename provided in the request and the MIME type declared in the headers.

Your proposed solution removes the MIME type check entirely, relying only on file size and extension:

$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));

if ($_FILES['file']['size'] < 20000 && in_array($extension, $allowedExts)) {
    // Proceed with upload
}

This approach is significantly safer than trusting $_FILES['type'], but it is not secure enough. An attacker can simply rename a script named malicious.sh to backup.jpg. The extension check will pass because the filename ends in .jpg, and the size check passes, yet the file contains executable code rather than an image.

To truly validate that a file is actually an image, you must inspect the binary content of the file itself. This is known as "magic number" detection or MIME type sniffing. The finfo extension in PHP provides a robust way to do this without needing external libraries like the mime_content_type() function, which can sometimes be inconsistent across environments.

Here is a more secure implementation that validates the actual file content:

$allowedExts = ['gif', 'jpeg', 'jpg', 'png'];
$maxSize = 20000;

if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $tmpName = $_FILES['file']['tmp_name'];
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    
    // Get the actual MIME type by sniffing the file content
    $mimeType = $finfo->file($tmpName);

    // Validate against both extension and actual content
    if (
        in_array(pathinfo($tmpName, PATHINFO_EXTENSION), $allowedExts) &&
        in_array($mimeType, ['image/gif', 'image/jpeg', 'image/png'])
    ) {
        // The file is safe to process
    } else {
        // File extension or content does not match allowed types
        die('Invalid file type.');
    }
}

This approach decouples the validation logic from user-controlled headers. It checks that the filename ends with an allowed extension and verifies that the actual bytes on disk start with the magic numbers for a valid image (e.g., 89 50 4E 47 for PNG). This prevents scenarios where an attacker renames a non-image file to bypass basic checks.

If you are working within a Laravel application, consider leveraging its built-in validation rules and filesystem helpers, which handle these security concerns more abstractly. You can define strict rules in your controller that ensure only valid image files are processed before storage occurs. For more details on securing file uploads in modern PHP stacks, see https://laravelcompany.com.

Always remember: never trust the client. Always verify the content.

Our network