PHP implementation code for getting the binary file header to quickly determine the file type
Source: Internet
Author: User
The following code identifies the actual type of a file by reading the file header information. If you need a friend, you can refer to it. generally, we judge the file type based on the file extension, but this is very unreliable and can be easily avoided by modifying the extension, it is generally necessary to read the file information for identification. PHP extensions provide functions such as exif_imagetype to read Image file types. However, in many cases, extensions are not necessarily installed, sometimes you need to identify the file type on your own.
The following code identifies the actual type of a file by reading the file header information.
The 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;
}
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.