Home > Article > Backend Development > How to get the mime type of a file through php
php Method to get file mime type
1. Use mime_content_type method
string mime_content_type ( string $filename ) Returns the MIME content type for a file as determined by using information from the magic.mime file.
<?php $mime_type = mime_content_type('1.jpg'); echo $mime_type; // image/jpeg ?>
But this method was abandoned in php5.3 and above, and the official recommendation is to use the fileinfo method instead.
2. Use Fileinfo method (official recommendation)
Using fileinfo requires installationphp_fileinfo Extension.
If installed, you can find it in the extension_dir directoryphp_fileinfo.dll(windows),fileinfo.so(linux)
Open php.ini, remove the ";" before extension=php_fileinfo.dll, and then restart apache.
<?php $fi = new finfo(FILEINFO_MIME_TYPE); $mime_type = $fi->file('1.jpg'); echo $mime_type; // image/jpeg ?>
#3. Use the image_type_to_mime_type method (can only handle image types)
Using the exif_imagetype method requires installationphp_exifExtension, and you need to install the php_mbstring extension
If it is installed, you can find it in the extension_dir directoryphp_exif.dll(windows), exif.so(linux)
Open php.ini, remove the "," before extension=php_mbstring.dll, extension=php_exif.dll, and then restart apache
<?php $image = exif_imagetype('1.jpg'); $mime_type = image_type_to_mime_type($image); echo $mime_type; // image/jpeg ?>
#Tips:If you use the suffix of the file name to judge, because the file suffix can be modified, it will not be judged by using the file suffix. precise.
This article explains how to obtain the file mime type through php. For more related content, please pay attention to the php Chinese website.
Related recommendations:
How to get all the Video information of a certain User on Youtube through php
php Character encoding conversion class related content
Explanation of the performance between php implode/explode, serialize, json, msgpack
The above is the detailed content of How to get the mime type of a file through php. For more information, please follow other related articles on the PHP Chinese website!