How to get the mime type of a file through php

jacklove
Release: 2023-03-31 08:10:02
Original
4052 people have browsed it

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.
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 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(&#39;1.jpg&#39;);
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 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(&#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, 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!

Related labels:
php
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