且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 上传文件验证

更新时间:2023-09-29 22:15:16

许多文件格式都有一组非常标准的起始字节来指示格式.如果您对前几个字节进行二进制读取并针对已知格式的起始字节进行测试,那么它应该是确认文件类型与扩展名匹配的一种相当可靠的方法.

Lots of file formats have a pretty standard set of starting bytes to indicate the format. If you do a binary read for the first several bytes and test them against the start bytes of known formats it should be a fairly reliable way to confirm the file type matches the extension.

例如JPEG的起始字节为0xFF、0xD8;就像这样:

For example, JPEG's start bytes are 0xFF, 0xD8; so something like:

$fp = fopen("filename.jpg", "rb");
$startbytes = fread($fp, 8);
$chunked = str_split($startbytes,1);
if ($chunked[0] == 0xFF && $chunked[1] == 0xD8){
    $exts[] = "jpg";
    $exts[] = "jpeg";
}

然后检查分机.

可以工作.