How should you validate an uploaded file's type and size before accepting it, and why is checking only the file extension considered insufficient for security?
Short answer
You should validate an uploaded file's actual content type using functions that inspect the file's real content, such as checking its MIME type through PHP's fileinfo extension, rather than trusting only the file extension or the client provided MIME type in $_FILES, since both…
Advertisement
AModel answer
You should validate an uploaded file's actual content type using functions that inspect the file's real content, such as checking its MIME type through PHP's fileinfo extension, rather than trusting only the file extension or the client provided MIME type in $_FILES, since both of those can be easily manipulated by a malicious user, and you should also enforce a maximum file size both in your PHP configuration and in your application code to prevent excessively large uploads.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $_FILES['document']['tmp_name']);
if (!in_array($mimeType, ['image/jpeg', 'image/png'])) {
throw new InvalidArgumentException('Invalid file type');
}Real-world example
An image upload feature verifies the actual content of an uploaded file using the fileinfo extension rather than trusting the file extension alone, blocking a malicious user who attempted to disguise an executable script as an image simply by renaming its extension.
Likely follow-ups
- What is the difference between the client provided MIME type and the actual detected MIME type?
- How do you configure the maximum upload file size at the PHP configuration level?
Related topics