How to get file type by file header in PHP

We usually check file type by file name, for example, a file call 11.jpg, we can split “jpg” and judge this file is an image. However, do you have other way to do this?

Today we introduce judge file type by file header information, we realize it by php script.

Look at source code below:

<?php
 //file will be checked
 $filename = "11.jpg";

$file = fopen($filename, "rb");
 $bin = fread($file, 2); //read 2 byte
 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 '.$fileType.' file:'.$typeCode;

//you also can use function mime_content_type in linux system
 echo mime_content_type('test1.gif') . "\n";
 echo mime_content_type('test2.php');
 ?>

,