PHP implementation code for taking binary file header to quickly determine file type_PHP tutorial

WBOY
Release: 2016-07-21 15:00:23
Original
866 people have browsed 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. Generally, the file information must be read to identify it. The PHP extension provides functions like exif_imagetype. Read image file types, but in many cases the extension may not be installed, and sometimes you need to identify the file type yourself.

The following code shows how to identify the true type of the file by reading the file header information.

Copy code 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';
                                                                                                                5:
$file_type = 'zip';
break;
case 8297:
$file_type = 'rar';
break;
case 255216:
$file_type = 'jpg';
                break; 'gif';
break;
case 6677:
$file_type = 'bmp';
break;
case 13780:
$file_type = 'png';
break ;
default:
$file_type = 'unknown';
break;
}

echo $file , ' type: code:', $type_code, '
';

}


The output result of 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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328080.htmlTechArticleGenerally we judge the file type based on the file extension, but this is very unreliable and can be easily modified The extension is avoided. Generally, the file information must be read to identify it. P...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!