Home > Backend Development > PHP Tutorial > PHP takes binary file header and quickly determines file type_PHP tutorial

PHP takes binary file header and quickly determines file type_PHP tutorial

WBOY
Release: 2016-07-13 17:54:32
Original
985 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 changing the extension. Generally, the file information must be read to identify it.

$files = array('./test.jpg', 'test.png');
$fileTypes = array(
7790 => 'exe',
7784 => 'midi',
8075 => 'zip',
8297 => 'rar',
225216 => 'jpg',
7173 => 'gif',
6677 => 'bmp',
13780 => 'png',
);
foreach($files as $file) {
$fp = fopen($file, 'rb');
$bin = fread($fp, 2); // Read only the first two bytes
fclose($fp);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
$fileType = isset($fileTypes[$typeCode]) ? $fileTypes[$typeCode] : 'unknown';
echo $file , ' type : ', $fileType, ' code : ', $fileType, '
';
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477942.htmlTechArticleGenerally we judge the file type based on the file extension, but this is very unreliable and can be easily modified To avoid the extension, generally the file information must be read to identify it. ...
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