php - 检查二进制图像数据

标签 php binaryfiles

我需要通过检查二进制数据找到用户上传的文件类型,我找到了完美的解决方案,超过 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/

相关文章:

php - 查询 3 个表和一个 MAX

php - Mysql更新、替换和拼接

linux - 如何在不提取整个文件的情况下更改存档 (.ear) 文件中的文件

dart - 如何在 Dart 中检测文件是否为二进制(非文本)?

python - R readBin 与 Python 结构

javascript - 如何将变量发送到模态以显示从数据库php查询的值

php - WooCommerce 2.6 - 在达到特定数量触发免费送货时隐藏付费送货

php - 通知 : Array to string conversion

c# - 如何在 C# 中读取作为终端输入的二进制文件

python - 如何在Python中从二进制MP3文件中读取特定字节?