Detecting MIME types

Detecting MIME types – How to determine the MIME type of a file

Detecting the MIME type of a file

The most simple way to detect the MIME type of any file is to use MIME_Type's static autoDetect() method. It will try to determine the file's type and return it as a string. If an error occurs, a PEAR_Error object is returned.

By default, only the plain MIME type will be returned, without any comments or parameters. If you pass true as second parameter to the method, all available MIME parameters will be appended to the returned type.

Detecting the MIME type of a file

<?php
require_once 'MIME/Type.php';

$filename '/path/to/some/file.jpg';
echo 
MIME_Type::autoDetect($filename);
?>

The MIME type of the given file will be echoed.

Matching a MIME type

If you want to check if a certain MIME type matches a wildcard type, use the static wildcardMatch(). It takes the wildcard as first, and the type to be checked as second parameter. It returns true if the wildcard matches the MIME type, false if not.

Matching a wildcard type

<?php
require_once 'MIME/Type.php';

$filename '/path/to/some/file.jpg';
$type     MIME_Type::autoDetect($filename);

if (
MIME_Type::wildcardMatch('image/*'$type)) {
    echo 
'File ' $filename ' is an image.';
} else {
    echo 
'File is no image.';
}
?>