dongou2019 2012-11-22 19:16
浏览 43
已采纳

检查二进制图像数据

I need to find what kind of file user have upload by checking binary data, and I found perfect solution for that, over here

Just to be specific this is the function I'm using:

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;
}

Now my question is, how can I get bits for other file types, like .zip, .exe, mp3, mp4 etc... if there is some kind of list somewhere out there it would be great, though I would like to extract it myself and learn how all of this really works.

  • 写回答

3条回答 默认 最新

  • dreljie602951 2012-11-22 19:29
    关注

    What you're looking for is called file magic number.

    The magic number is a type of file signature - since sometimes it takes more than the magic number to identify the file.

    A (very) short list of such numbers can be found here. A larger list can be found here.

    File identification websites often times also mention the file magic number.

    In linux, the file command can be used to identify files. In PHP you can use the FileInfo set of functions to identify files.


    By the way, you did not specify the kind of files you want to identify. Sometimes, identification might be the wrong solution. For example, people used to want to identify files before passing them to GD or saving them on the server as images. In this case, identification is not really your job. Instead, use the following code:

    $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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集