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.';
}
?>
MIME_Type (Previous) How to get more information about a MIME type (Next)
Last updated: Sun, 21 Dec 2014 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report or add a note.
View this page in:

User Notes:

Note by: macfly@german-bash.org
You have to use the absolute path, otherwise it will give you a file-not-found-error
Note by: Pedro
I'm getting:" File "../uploads/Test.txt" doesn't exist "
But the file does exist..
What could it be?

thx