Validating file type
Learn to validate the uploaded file's type (MIME).
What is a MIME type?
Accepting an uploaded file without checking its type is dangerous; someone could upload a PHP script named .jpg. So you must validate the file type.
The MIME type is a label describing the file's content (e.g. image/png, application/pdf). PHP stores it in $_FILES['avatar']['type']; it is reported by the browser.
The browser-reported MIME type is not always honest; for more safety use mime_content_type() or finfo to read the real type. But the type field is enough to start.
The allowed types list
For validation, define the allowed MIME types as an array: $allowed = ['image/png', 'image/jpeg']. Then use in_array() to check whether the file's type is in the list.
Example: in_array($file['type'], $allowed, true). The third argument true enables strict comparison; no type casting. This matters for security.
Checking only the extension is not enough; an extension is easy to fake. The MIME type offers a more reliable check.
Exercise The validateType function
Write a validateType(array $file, array $allowed): string function. Inside it, check the type with in_array($file['type'], $allowed, true). If it matches, return 'Valid: ' . $file['type']; otherwise return 'Rejected: ' . $file['type']. For testing, define $_FILES['avatar'] (name: 'profile.png', type: 'image/png', tmp_name: '/tmp/phpAbCd.tmp', error: 0, size: 102400), define $allowed = ['image/png', 'image/jpeg'] and write echo validateType($_FILES['avatar'], $allowed) . "\n".
Show example solution
' or 'Rejected: ' + type.
Example solution:
<?php
// Validate file type
function validateType(array $file, array $allowed): string {
if (in_array($file['type'], $allowed, true)) {
return "Valid: " . $file['type'];
}
return "Rejected: " . $file['type'];
}
$_FILES['avatar'] = [
'name' => 'profile.png',
'type' => 'image/png',
'tmp_name' => '/tmp/phpAbCd.tmp',
'error' => 0,
'size' => 102400
];
$allowed = ['image/png', 'image/jpeg'];
echo validateType($_FILES['avatar'], $allowed) . "\n";
Test yourself
-
Which check is more reliable for file type?
- Checking the MIME type
- Checking the file extension
- Checking only the file name
- Accepting without any check
Show answer
Checking the MIME type — Correct. The MIME type is more reliable than the extension.
-
Match extensions and MIME types
- .png
- image/png
- .jpg
- image/jpeg
- .gif
- image/gif
- application/pdf
-
Type check with in_array
if (in_array($file['type'], ____, true)) { return true; }Show answer
if (in_array($file['type'], $allowed, true)) { return true; }