Detailed Explanation of PHP File Type Check and fileinfo Module Installation and Use

  • 2021-12-11 07:14:49
  • OfStack

In the development of web system, file uploading function is a very common function. There is a very critical step in the development of this function: file type check, which plays a very important role in system security and is also what a qualified programmer must do. So how do you do file type checking in PHP?

File type checking method

Before answering this question, first look at your version of PHP, because different versions may have different methods:

Prior to PHP 5.3, you can use the mime_content_type method to check;

However, after PHP 5.3, this method was abandoned because there are many problems in this method.

Here, it is suggested that you upgrade the following versions of PHP 5.3, because PHP7 has come out, and you are still using PHP5.2 or even older versions, which is totally inconsistent with the style of rapid iteration and keeping pace with the times in the Internet circle. No kidding, PHP7 does have a great performance improvement.

So, let's just talk about the file type checking method after PHP 5.3: using fileinfo library

Usage of fileinfo Module

Introduction to the fileinfo module in the official document: The function in this module guesses the content type and encoding of a file by looking for a specific magic byte sequence at a given position in the file. Although it is not 100% accurate, it usually works well.

Let's start with the code


$fileName = 'www.pythontab.com.png';
$fip = finfo_open(FILEINFO_MIME); //  Return  mime  Type 
echo finfo_file($fip, $fileName);
finfo_close($fip);

In this way, you can directly output the Mime type of the file, which is relatively simple.

fileinfo Module Installation

However, PHP does not open fileinfo module by default, and this library will not be installed by default, so we have to install it ourselves before we can use it.

Let's look at how to install the fileinfo module:

1 Download Expansion Pack

Download according to their version number


wget -O php-5.6.25.tar.gz http://cn2.php.net/get/php-5.6.25.tar.gz/from/this/mirror

You can also download the fileinfo package separately here


wget -O http://pecl.php.net/get/Fileinfo-1.0.4.tgz

2 Decompression


tar -zxvf php-5.6.25.tar.gz

3 Enter the Extended Directory


cd /soft_src/php/php-5.6.25/ext/fileinfo

4 Compile & & Installation


/usr/local/php/bin/phpize
./configure -with-php-config=/usr/local/php/bin/php-config
make && make install

In this way, a new fileinfo. so file will be generated in the default extension directory of the system

5 Modify the php. ini file


vim /usr/local/php/etc/php.ini

Accession: extension=fileinfo. so

Restart php, and the installation is complete


Related articles: