Why Checking File Uploads by MIME Type Alone Is a Trap
When handling file uploads, developers frequently encounter the exact scenario you described: checking $_FILES["file"]["type"] against a string like "text/csv" and finding that the logic fails for legitimate CSV files. The root cause isn't a syntax error in your PHP code; it is a fundamental misunderstanding of how web browsers and server environments report file metadata.
The value stored in $_FILES["file"]["type"] is not an intrinsic property of the file itself. Instead, it is a string provided by the sending user agent (the browser), derived from the Content-Type header attached to the HTTP request. This header is often set automatically based on the file extension or guessed content, and it is notoriously unreliable for security-critical logic.
Consider that modern browsers might report a file as "application/octet-stream" regardless of whether it is a CSV, an image, or a malicious script if the MIME type cannot be determined with certainty. Conversely, some users manually configure their browsers to strip MIME types entirely. If your validation logic relies solely on $_FILES["file"]["type"], you are trusting the client rather than verifying the actual content of the file. This opens the door for attackers to rename a malicious executable as myfile.csv and bypass your filter if they can manipulate the browser's headers or if the server environment is misconfigured regarding MIME type detection.
The solution is to validate the file based on its actual content, not its declared type. The most robust method in PHP is using the finfo extension to perform a magic number check. This function analyzes the binary data at the start of the file stream to determine its true format, independent of what the browser claims it is.
Here is how you can implement this check securely:
$allowed_mime_types = [
'text/csv' => 'csv',
];
// Ensure the uploaded file is not empty
if (empty($_FILES['file']['error']) && $_FILES['file']['size'] > 0) {
// Get the file extension from the actual filename
$extension = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
// Create a finfo resource to check the MIME type of the uploaded data
$finfo = finfo_open(FILEINFO_MIME_TYPE, finfo_get_file(FINFO_FILE, '/etc/mime.types'));
if (!$finfo) {
throw new Exception('Failed to initialize file info detection.');
}
// Check the actual MIME type of the uploaded file content
$actual_mime_type = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);
// Validate against allowed types
if (in_array($actual_mime_type, ['text/csv'], true)) {
// Proceed with processing the CSV file
$filename = $_FILES['file']['name'];
$filepath = UPLOAD_DIR . '/' . $filename;
// Move and process as needed
move_uploaded_file($_FILES['file']['tmp_name'], $filepath);
} else {
throw new Exception('Invalid file type detected. Only CSV files are allowed.');
}
}
In this implementation, we explicitly check the actual_mime_type returned by finfo_file. By passing /etc/mime.types as a second argument to finfo_open, we ensure that PHP uses the system's MIME type database rather than relying on heuristics alone. This approach guarantees that even if an attacker sends a file with a fake CSV extension or a manipulated header, the server will detect the true content type based on the magic bytes at the start of the file.
There is another layer to consider: file extensions. While checking the extension ($extension) provides a simple sanity check, it should never be the sole validation method. However, combining the MIME type check with an extension whitelist adds a secondary defense-in-depth layer. Always ensure that the temporary file created by move_uploaded_file is secure and that you validate the original filename against a list of allowed characters to prevent path traversal attacks.
If you are working within the Laravel ecosystem, the laravelcompany.com documentation provides excellent resources on handling uploads with the Illuminate\Http\UploadedFile class, which abstracts much of this complexity while still encouraging strict validation rules.