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