Generally we are in accordance with the file extension to determine the file type, but this is very unreliable, easily by modifying the extension to avoid, it is generally necessary to read the file information to identify, PHP extension provides similar functions such as Exif_imagetype read the file type of the picture class, However, many times the extension does not have to be installed, and sometimes it is necessary to implement the work of identifying file types.
The following code shows that you are reading the file header information to identify the true type of the file.
Copy CodeThe code is as follows:
$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:
', $file _type, 'Code
', $type _code, '
';
}
This example outputs the result
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
http://www.bkjia.com/PHPjc/328080.html www.bkjia.com true http://www.bkjia.com/PHPjc/328080.html techarticle generally we are in accordance with the file extension to determine the file type, but this is very unreliable, easily by modifying the extension to avoid, it is generally necessary to read the file information to identify, P ...