PHP implementation to get file MIME type method _php tips

Source: Internet
Author: User
Tags mime file

The example in this article describes how PHP gets file MIME types. Share to everyone for your reference. Specifically as follows:

1. Using 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.

<?php 
$mime _type = Mime_content_type (' 1.jpg '); 
echo $mime _type; Image/jpeg 
?>

However, this method was discarded above php5.3, and the official proposal was to use the FileInfo method instead.

2. Using the Fileinfo method (official recommendation)

You need to install Php_fileinfo extensions with FileInfo.
If installed can be found in the Extension_dir directory Php_fileinfo.dll (Windows), Fileinfo.so (Linux)
Open the php.ini, put the extension=php_fileinfo.dll before the ";" Remove, and then restart Apache.

<?php 
$fi = new Finfo (fileinfo_mime_type); 
$mime _type = $fi->file (' 1.jpg '); 
echo $mime _type; Image/jpeg 
?>

3. Using the Image_type_to_mime_type method (only the image type can be processed)

Use the Exif_imagetype method to install the php_exif extension and need to install the php_mbstring extension
If installed can be found in the Extension_dir directory Php_exif.dll (Windows), Exif.so (Linux)
Open the php.ini, put the Extension=php_mbstring.dll, Extension=php_exif.dll before the "," remove, 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 determine, because the file suffix can be modified, so use the file suffix to judge is inaccurate.

I hope this article will help you with your PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.