Home > Backend Development > PHP Tutorial > How to get file mime type in php

How to get file mime type in php

WBOY
Release: 2016-08-08 09:32:06
Original
913 people have browsed it

php method to get the file mime type

1. Use the 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. 
Copy after login
<?php
$mime_type = mime_content_type(&#39;1.jpg&#39;);
echo $mime_type; // image/jpeg
?>
Copy after login

But this method was abandoned in php5.3 or above, and the official recommendation is to use the fileinfo method instead.

2. Use Fileinfo method (official recommendation)

Using fileinfo requires installing the php_fileinfo extension.

If it has been installed, it can be found in the extension_dir directory php_fileinfo.dll(windows), fileinfo.so(linux)

Open php.ini and change the " in front of extension=php_fileinfo.dll ;"Remove it and restart apache.

<?php
$fi = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $fi->file('1.jpg');
echo $mime_type; // image/jpeg
?>
Copy after login

3. Use the image_type_to_mime_type method (can only handle image types)

Using the exif_imagetype method requires installing the php_exif extension and the php_mbstring extension

If it has been installed, it can be in the extension_dir directory Find php_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(&#39;1.jpg&#39;);
$mime_type = image_type_to_mime_type($image);
echo $mime_type; // image/jpeg
?>
Copy after login

Tips:If you use the suffix of the file name to judge, because the file suffix can be modified, using the file suffix to judge will not be accurate.

The above introduces the method of obtaining the mime type of the file in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template