Upload DOC or PDF using PHP

Upload DOC or PDF using PHP

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

Stefan Bogdanescu

Founder & Senior Architect

The Hidden Trap in PHP File Upload Validation

When you switch from uploading images to documents, a common failure mode appears: the code that worked perfectly for JPEGs suddenly rejects every DOC or PDF file with an "Invalid File" message. This happens even when the file size is tiny—often under 30KB—and well below your configured limits. The culprit isn't the file itself; it's a fundamental misunderstanding of how PHP determines file types and where that logic breaks down for binary formats like documents.

In the provided example, the validation relies on two distinct sources of truth: the MIME type reported by the browser ($_FILES["file"]["type"]) and the file extension extracted from the filename. The logic attempts to match these against a whitelist. However, this approach contains several critical flaws that specifically impact non-image files.

The primary issue lies in the assumption that $_FILES["file"]["type"] is reliable for documents. For images, browsers are generally consistent in reporting image/jpeg, image/png, etc. But for documents, the client-side behavior varies wildly. A user might select a file using Chrome, which reports application/msword, while Firefox might report application/vnd.ms-word.document.macroEnabled.12 or simply leave it blank if the browser doesn't recognize the specific MIME type. Furthermore, many users rename files to .pdf or .docx without ensuring the internal binary signature matches that extension. If a user renames a text file to report.pdf, your check passes the extension test but fails the MIME type test because the actual content is not PDF data.

The code snippet provided uses explode(".", $_FILES["file"]["name"]) to extract the extension. This method is fragile. It assumes the filename always follows the pattern [name].[extension]. If a file is named my.report.pdf, the logic only captures pdf. More dangerously, if a user uploads a file named readme.txt but manually changes the extension in their browser to .doc before submitting, the code will see "doc" as the extension. However, the MIME type check will likely fail or pass unpredictably depending on how the server processed it.

A more robust validation strategy involves bypassing the user's filename and relying entirely on the file's binary signature (magic bytes) using finfo_file(). This function reads the first few bytes of the uploaded file in $_FILES["file"]["tmp_name"] and compares them against a database of known signatures. It doesn't care what the file is named; it only cares what it actually is.

Here is a revised approach that addresses these pitfalls:

$allowedExts = array("pdf", "doc", "docx");
$mimeTypeMap = [
    'application/pdf' => 'pdf',
    'application/msword' => 'doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
    // Add other common document MIME types here
];

$finfo = new finfo(FILEINFO_MIME_TYPE);
$actualMimeType = $finfo->file($_FILES["file"]["tmp_name"]);

// Verify size first to prevent DoS attacks
if ($_FILES["file"]["size"] > 20000) {
    echo "Invalid file.";
    exit;
}

// Check if the actual MIME type is in our whitelist
if (!in_array($actualMimeType, array_keys($mimeTypeMap))) {
    echo "Invalid file type detected.";
    exit;
}

// Ensure the extension matches the detected content type
$extension = strtolower(pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION));
if ($mimeTypeMap[$actualMimeType] !== $extension) {
    echo "File extension does not match file content.";
    exit;
}

// Only move the file if all checks pass
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);

This implementation uses finfo to derive the truth about the file's content. It then cross-references that truth with a whitelist of allowed MIME types and ensures the filename extension aligns with that reality. This prevents users from tricking your server by renaming harmless files or uploading malicious scripts disguised as documents.

If you are building this feature within a modern PHP framework, consider leveraging existing packages that handle file validation more comprehensively. For instance, LaravelCompany offers solutions that integrate seamlessly into Laravel applications, providing helper methods to validate uploaded files against known magic byte signatures without reinventing the wheel.

Remember that relying solely on $_FILES["file"]["type"] is a recipe for inconsistent behavior across different browsers and operating systems. By validating content signatures and enforcing strict extension-to-content matching, you create a secure boundary that accepts legitimate documents while rejecting disguised threats or mislabeled files.

Our network