PHP uses the binary file header to quickly determine the implementation code of the file type. Generally, we determine the file type based on the file extension, but this is not reliable. we can easily avoid it by modifying the extension. generally, we must read the file information to identify it, P we generally judge the file type according to the file extension, but this is very unreliable and can be easily avoided by modifying the extension. generally, we must read the file information for identification, PHP extensions provide functions like exif_imagetype to read Image file types. However, many extensions are not necessarily installed. sometimes you need to identify file types 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;
}
Echo $ file, 'type:', $ File_type ,'Code:', $ Type_code ,'
';
}
Output result in this example
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
...