Oihana PHP

validateMimeType.php

Table of Contents

Functions

validateMimeType()  : void
Validate the MIME type of a file against a list of allowed types.

Functions

validateMimeType()

Validate the MIME type of a file against a list of allowed types.

validateMimeType(string $file, array<string|int, mixed> $allowedMimeTypes) : void
Parameters
$file : string

Path to the file to validate.

$allowedMimeTypes : array<string|int, mixed>

List of allowed MIME types. Can include strings or arrays of strings.

Tags
throws
FileException

If the MIME type is not allowed or cannot be determined.

example

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:

  • 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.
author

Marc Alcaraz (ekameleon)

since
1.0.0

        
On this page

Search results