Home  >  Article  >  Backend Development  >  PHP implementation code for reading file headers to determine file type_PHP tutorial

PHP implementation code for reading file headers to determine file type_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:00:25896browse

The php code implements reading the file header to determine the file type, and supports suffixes such as pictures, rar, and exe.
Case:

Copy code The code is as follows:

//For the path of the picture, you can use absolute paths such as d:/upload/11.jpg
$file = fopen($filename, "rb");
$bin = fread($file, 2); //Read only 2 bytes
fclose($file);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($ strInfo['chars1'].$strInfo['chars2']);
$fileType = '';
switch ($typeCode) {
case 7790: $fileType = 'exe'; break;
case 7784: $fileType = 'midi'; break;
case 8297: $fileType = 'rar'; break;
case 255216: $fileType = 'jpg'; break;
case 7173: $fileType = 'gif'; break;
case 6677: $fileType = 'bmp'; break;
case 13780: $fileType = 'png'; break;
default: echo'unknown';
}
echo 'This is a '.$fileType.' file:'.$typeCode;

Case:
Copy the code The code is as follows:

?>
//There is also a function in php under Linux that can determine the file type
echo mime_content_type('11.gif') . "n";
echo mime_content_type('22.php');
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328079.htmlTechArticlephp code reads the file header to determine the file type, and supports suffixes such as pictures, rar, exe, etc. Case: Copy the code. The code is as follows: ?php $filename = "11.jpg"; //The path to the image can be used...
Statement:
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