PHP Fetch binary file header quick to determine file type implementation code _php tips

Source: Internet
Author: User
Tags rar
Generally we are in accordance with the file name extension to determine the file type, but this is very unreliable, easily by modifying the extension to avoid, the general must read the file information to identify, PHP extension provides a function like Exif_imagetype to read the picture class file type, But most of the time the extensions don't have to be installed, and sometimes you need to do the work of identifying file types yourself.

The following code shows that you recognize the true type of the file by reading the header information.
Copy Code code as follows:

<?php
$files = Array (
' C:\1.jpg ',
' C:\1.png ',
' C:\1.gif ',
' C:\1.rar ',
' C:\1.zip ',
' C:\1.exe ',
);
foreach ($files as $file) {
$fp = fopen ($file, "RB");
$bin = Fread ($fp, 2); Read Only 2 bytes
Fclose ($FP);
$str _info = @unpack ("C2chars", $bin);
$type _code = intval ($str _info[' chars1 '). $str _info[' chars2 ']);
$file _type = ';
Switch ($type _code) {
Case 7790:
$file _type = ' exe ';
Break
Case 7784:
$file _type = ' midi ';
Break
Case 8075:
$file _type = ' zip ';
Break
Case 8297:
$file _type = ' rar ';
Break
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
}

echo $file, ' type: <b> ', $file _type, ' </b> code:<b> ', $type _code, ' </b><br/> ';

}

This example outputs the results
C:\1.jpg type:jpg code:255216
C:\1.png Type:png code:13780
C:\1.gif Type:gif code:7173
C:\1.rar Type:rar code:8297
C:\1.zip Type:zip code:8075
C:\1.exe Type:exe code:7790

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.