我需要通过检查二进制数据找到用户上传的文件类型,我找到了完美的解决方案,超过 here
具体来说,这是我正在使用的功能:
function getImgType($filename) {
$handle = @fopen($filename, 'r');
if (!$handle)
throw new Exception('File Open Error');
$types = array('jpeg' => "\xFF\xD8\xFF", 'gif' => 'GIF', 'png' => "\x89\x50\x4e\x47\x0d\x0a", 'bmp' => 'BM', 'psd' => '8BPS', 'swf' => 'FWS');
$bytes = fgets($handle, 8);
$found = 'other';
foreach ($types as $type => $header) {
if (strpos($bytes, $header) === 0) {
$found = $type;
break;
}
}
fclose($handle);
return $found;
}
现在我的问题是,如何获取其他文件类型的位,例如 .zip、.exe、mp3、mp4
等...如果某处有某种列表,它会很棒,尽管我想自己提取它并了解所有这些的真正工作原理。
最佳答案
您要找的是 file magic number .
魔数(Magic Number)是一种文件签名 - 因为有时它需要比魔数(Magic Number)更多来识别文件。
可以找到此类数字的(非常)简短列表 here .可以找到更大的列表 here .
文件识别网站也经常提到文件魔数(Magic Number)。
在 Linux 中,file
命令可用于识别文件。
在 PHP 中,您可以使用 FileInfo一组用于识别文件的函数。
顺便说一下,您没有指定要识别的文件类型。有时,识别可能是错误的解决方案。例如,人们过去常常希望在将文件传递给 GD 或将其作为图像保存在服务器上之前对其进行识别。 在这种情况下,识别实际上不是您的工作。相反,请使用以下代码:
$data = file_get_contents('data.dat'); // File might eventcontain a JPG...it is
// still loaded without problems!
$image = imagecreatefromstring($data); // ... since this function just needs the
// file's data, nothing more.
关于php - 检查二进制图像数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13518852/