Basic usage: validate that an uploaded file is a PDF or plain text file.
use function oihana\files\validateMimeType;
use oihana\files\exceptions\FileException;
$file = __DIR__ . '/example.txt';
file_put_contents($file, 'Some text content');
try
{
validateMimeType($file, ['text/plain', 'application/pdf']);
echo "File is valid.";
}
catch ( FileException $e )
{
echo "Error: " . $e->getMessage();
}
unlink($file);
Accepting multiple MIME types (grouped by type):
$allowedTypes =
[
['image/png', 'image/jpeg'],
['application/pdf'],
];
validateMimeType('photo.jpg', $allowedTypes);
Error example:
try
{
validateMimeType('fake.exe', ['image/png', 'image/jpeg']);
}
catch (FileException $e)
{
echo "Validation failed: " . $e->getMessage();
}
Notes:
- Both the detected type and the allowed ones are compared by the reference name of their format
(normalizeMimeType()) :
['audio/wav'] accepts a WAV file that finfo reports as
audio/x-wav. Only names of the same format meet — an image never passes for a script. The
error message quotes the type as finfo reported it.
- Allowing
audio/webm allows a WebM video too : finfo reports video/webm for both, the
container being the same.
- This function uses
mime_content_type(), which relies on the system's file command or magic database.
- For consistent results across platforms, ensure the PHP
fileinfo extension is enabled.