PHP: How to properly check MIME type of a file?

PHP: How to properly check MIME type of a file?

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

Stefan Bogdanescu

Founder & Senior Architect

The MIME Type Trap: Validating Uploads Beyond File Extensions

Relying solely on file extensions to validate uploads is a well-documented security anti-pattern. An attacker can rename malicious.exe to image.jpg, and if your application trusts the extension alone, it will attempt to store and potentially serve an executable as if it were an image. While checking the extension provides a basic layer of defense, validating the MIME type adds a critical second line of verification. However, simply calling finfo_file() or reading $_FILES['type'] is often insufficient because these methods rely on client-side headers that are trivial to spoof.

To properly secure your upload logic, you must verify the MIME type against the actual file content, not just its declared type. The standard PHP function for this is finfo_file(), which uses the system's magic number database to inspect the binary header of the uploaded file. This approach bypasses client manipulation because magic numbers are structural signatures embedded in the file format itself.

Here is how you can integrate a robust MIME check into your existing workflow, specifically targeting the point where you have successfully moved the file but before committing it further or serving it.

$allowedMimes = [
    'image/jpeg' => ['jpg', 'jpeg'],
    'image/png'  => ['png'],
];

// Ensure the extension is still valid as a secondary check
if (!in_array(strtolower($aFileProperties["extension"]), $aExtensionWhitelist)) {
    echo "Bestands type niet toegestaan";
    continue;
}

// Create a finfo resource using the system magic database
$finfo = finfo_open(FILEINFO_MIME_TYPE, false, FILEINFO_MIME_USE_COMPRESS);

if ($finfo) {
    $detectedMime = finfo_file($finfo, $_FILES['Filename']['tmp_name'][$iAmountOfFiles]);
    
    // Close the resource as we are done with it for this file
    finfo_close($finfo);

    // Verify the detected MIME type matches an allowed image type
    if (!in_array(strtolower($detectedMime), ['image/jpeg', 'image/png'])) {
        echo "Ongeldig bestandstype. Alleen JPG en PNG worden toegestaan.";
        continue;
    }
} else {
    // Handle the case where finfo is not available (e.g., missing magic database)
    echo "MIME-check niet beschikbaar op deze server.";
    continue;
}

// Proceed with moving the file and saving metadata
$sTarget = ROOT.BACKEND."/pages/bezienswaardigheden-toevoegen/uploads/";
$sUniqueFileNameHash = hash('adler32', time().rand());
$Filename = basename($aFileProperties["filename"]."-".$sUniqueFileNameHash.".".strtolower($aFileProperties["extension"]));

if(move_uploaded_file($_FILES['Filename']['tmp_name'][$iAmountOfFiles], $sTarget.$Filename)) {
    // File is now safe to store in the database or serve to users
}

The core of this solution lies in finfo_open and finfo_file. The second argument to finfo_open is set to false, which instructs PHP to use the system's magic number database rather than reading it from a specific MIME type mapping file. This ensures that the check is based on the actual binary structure of the uploaded data.

A critical trade-off exists here: finfo_file() requires the system's magic database to be installed and configured correctly. On many Linux distributions, this involves installing packages like libmagic (on Debian/Ubuntu) or file (on RHEL/CentOS). If the magic database is missing, finfo_open will return false, and your validation logic must handle this gracefully without crashing the upload process.

Another pitfall is the distinction between MIME type and file extension. While they often align for legitimate files, they can diverge for corrupted or renamed files. For instance, a GIF image with a .jpg extension might still have a magic number indicating image/gif. By strictly enforcing that the detected MIME type must be one of your allowed list (image/jpeg or image/png) and ignoring the extension mismatch in such cases, you prevent serving the wrong file type.

In production environments where you cannot control the underlying operating system packages, consider using a dedicated library like mimesniff or implementing a custom header parser that reads the first few bytes of the file directly. This removes dependency on external system libraries and ensures consistent behavior across different server configurations.

If you are using Laravel, the Illuminate\Http\UploadedFile facade offers similar functionality via the getMimeType() method when combined with finfo. However, always remember to validate against both the extension and the content-derived MIME type for maximum security. For more advanced file validation strategies in Laravel, refer to the resources available at https://laravelcompany.com.

Our network