Debugging File Upload Validation Logic in PHP
When building an upload form, it's common to encounter logic that fails silently or behaves unexpectedly. You might expect a validation check for file size and type to handle all four scenarios correctly: valid/valid, valid/invalid, invalid/valid, and invalid/invalid. However, your current implementation consistently triggers the "Invalid file type" message whenever the file exceeds 2 megabytes, regardless of whether the MIME type is correct or incorrect.
The root cause lies in the use of an elseif statement. In your provided code snippet:
if (($file_size > 2097152)){
// Handle size error
}
elseif (
($file_type != "application/pdf") &&
// ... other types
){
// Handle type error
}
An if-elseif chain evaluates conditions sequentially and stops at the first match. When a file is larger than 2MB, the first condition ($file_size > 2097152) becomes true. The code immediately enters that block, displays the size error, and skips the elseif block entirely. Consequently, the validation for the file type never runs for oversized files. This explains why scenario #3 (incorrect size, correct type) displays a type error messageâit doesn't; it actually displays the size errorâbut if your logic were inverted or if you are misinterpreting the output, the flow is strictly top-down. More critically, if you intended to show both errors, an elseif prevents that from ever happening.
To fix the immediate logic issue where one error masks another, you must decouple these checks. Use independent if statements instead of chaining them with elseif. This ensures that every validation rule is evaluated regardless of other failures:
if (isset ($_FILES['uploaded_file'])) {
$file_size = $_FILES['uploaded_file']['size'];
$file_type = $_FILES['uploaded_file']['type'];
// Check size first
if ($file_size > 2097152) {
$message = 'File too large. File must be less than 2 megabytes.';
echo '<script type="text/javascript">alert("'.$message.'");</script>';
}
// Check type independently
if (
$file_type != "application/pdf" &&
$file_type != "image/jpeg" &&
$file_type != "image/jpg" &&
$file_type != "image/gif" &&
$file_type != "image/png"
) {
$message = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
echo '<script type="text/javascript">alert("'.$message.'");</script>';
}
// If no errors occurred
if (empty($message)) {
store_uploaded_file($id);
} else {
// Optional: Handle multiple errors or log them
$errors = [];
if ($file_size > 2097152) $errors[] = 'Size';
if (is_invalid_type($file_type)) $errors[] = 'Type';
if (!empty($errors)) {
echo '<script type="text/javascript">alert("Multiple errors: " + "' . implode(', ', $errors) . '");</script>';
}
}
}
However, relying solely on $_FILES['uploaded_file']['type'] is a significant security risk. PHP determines the MIME type based on the file extension or internal heuristics, which can be easily spoofed by renaming a malicious script to .jpg. An attacker could upload a PHP shell named shell.jpg, and PHP would report the type as image/jpeg.
To mitigate this, always verify the actual content of the file using a whitelist-based validation function. The finfo extension provides a robust way to detect the true MIME type based on file data:
if (function_exists('finfo_file')) {
$file_info = finfo_open(FILEINFO_MIME_TYPE, new finfo(FILEINFO_MIME_TYPE));
$actual_type = finfo_file($file_info, $_FILES['uploaded_file']['tmp_name']);
} else {
// Fallback if finfo is not available
$actual_type = $_FILES['uploaded_file']['type'];
}
// Whitelist check against the actual type
$allowed_types = ['application/pdf', 'image/jpeg', 'image/gif', 'image/png'];
if (!in_array($actual_type, $allowed_types)) {
// Handle invalid type
}
Furthermore, consider moving this logic into a framework if you are not already using one. Laravel provides elegant helpers like Request::file('uploaded_file')->isValid() which handles size limits and MIME type checking out of the box, reducing the surface area for human error. For more complex requirements, such as strict file extension validation alongside MIME checks, packages like spatie/laravel-filesystem can streamline the process.
Finally, remember to check server-side configuration. Even if your PHP code allows a file, directives in php.ini or .htaccess might override these settings. Ensure that upload_max_filesize and post_max_size are set appropriately to match your application logic, preventing silent failures where files are accepted by PHP but rejected by the web server during processing.
