PHP does not accurately determine the file type by extension

Source: Internet
Author: User
Tags unpack
This article mainly introduces the method of PHP not to accurately determine the file type through the extension, involving PHP Finfo_file method and binary stream for the file type of the relevant operation skills, the need for friends can refer to the following

The examples in this paper describe how PHP implementations do not accurately determine file types by extension. Share to everyone for your reference, as follows:

The first of these methods

Through PHP'sfinfo_file()

$handle =finfo_open (fileinfo_mime_type),//this function opens a magic database and returns its resource. $fileInfo =finfo_file ($handle, '/test.txt ');//Return information about a filefinfo_close ($handle);p Rint_r ($fileInfo echo ' =========== ' \ n ';

Other than that

finfo_buffer: Return information about a string buffer
finfo_close: Close FileInfo Resource
mime_content_type:D etect mime content-type for a file (deprecated)

The second method of

Get file content from a binary stream

$fp =fopen (' Test.txt ', ' r ')///actual is Image/png$bin = Fread ($fp, 2); Read-only 2-byte fclose ($fp), $str _info = @unpack ("C2chars", $bin)//unpack data from binary String$type_code = intval ($str _info[' Chars1 ']. $str _info[' chars2 ');//Get The integer value of a variable$file_type = "; switch ($type _code) {case 7790: $file _ty pe = ' exe '; break;case 7784: $file _type = ' midi '; break;case 8075: $file _type = ' zip '; break;case 8297: $file _type = ' rar '; Brea K;case 255216: $file _type = ' jpg '; break;case 7173: $file _type = ' gif '; break;case 6677: $file _type = ' bmp '; Break;case 13780: $file _type = ' png '; Break;default: $file _type = ' unknown '; break;}

The above is the whole content of this article, I hope that everyone's study has helped.


Related Article

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.