Common PHP Functions for Determining File Types
This article explains several built‑in PHP functions—mime_content_type, finfo_file, pathinfo, and getimagesize—used to detect a file's MIME type or extension, showing their syntax, usage examples, and important considerations such as required extensions and potential limitations.
In PHP, determining a file's type is essential for operations such as image resizing or cropping, and several built‑in functions can be used for this purpose.
mime_content_type
Before PHP 5.3 the mime_content_type function could retrieve a file's MIME type. Its signature is string mime_content_type ( string $filename ) . Example usage shows how to obtain and echo the MIME type of 'test.jpg' . The function works for many common types but may return incorrect results for some files and is not supported for all types.
finfo_file
Since PHP 5.3 the finfo_file function, part of the fileinfo extension, can be used to get a file's MIME type. Its signature is finfo finfo_file ( resource $finfo , string $filename [, int $options = FILEINFO_NONE [, resource $context ]] ) . An example demonstrates opening a finfo resource with FILEINFO_MIME_TYPE , calling finfo_file , and echoing the result. The fileinfo extension must be enabled.
pathinfo
The built‑in pathinfo function returns an array with path information, including dirname, basename, extension, and filename. Its signature is array pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] ) . An example shows extracting the file extension of 'test.jpg' .
getimagesize
To check whether a file is an image, the getimagesize function can be used. Its signature is array|false getimagesize ( string $filename [, array &$imageinfo ] ) . The function returns false for non‑image files; an example demonstrates a conditional check and output. It requires the GD extension to be enabled.
These functions each have advantages and limitations; choose the appropriate one based on your environment and needs, keeping in mind that MIME detection relies on file headers and may fail for malformed files.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.