mrd*_*iri 144 php zip rar mime-types
我正在开发一个简单的php上传脚本,用户只能上传ZIP和RAR文件.
我应该使用哪些MIME类型来检查$_FILES[x][type]?(请完整清单)
谢谢..
Gfy*_*Gfy 241
来自freedompeace,Kiyarash和Sam Vloeberghs的答案:
.rar application/x-rar-compressed, application/octet-stream
.zip application/zip, application/octet-stream, application/x-zip-compressed, multipart/x-zip
Run Code Online (Sandbox Code Playgroud)
我也会检查文件名.以下是检查文件是RAR还是ZIP文件的方法.我通过创建一个快速命令行应用程序来测试它.
<?php
if (isRarOrZip($argv[1])) {
echo 'It is probably a RAR or ZIP file.';
} else {
echo 'It is probably not a RAR or ZIP file.';
}
function isRarOrZip($file) {
// get the first 7 bytes
$bytes = file_get_contents($file, FALSE, NULL, 0, 7);
$ext = strtolower(substr($file, - 4));
// RAR magic number: Rar!\x1A\x07\x00
// http://en.wikipedia.org/wiki/RAR
if ($ext == '.rar' and bin2hex($bytes) == '526172211a0700') {
return TRUE;
}
// ZIP magic number: none, though PK\003\004, PK\005\006 (empty archive),
// or PK\007\008 (spanned archive) are common.
// http://en.wikipedia.org/wiki/ZIP_(file_format)
if ($ext == '.zip' and substr($bytes, 0, 2) == 'PK') {
return TRUE;
}
return FALSE;
}
Run Code Online (Sandbox Code Playgroud)
请注意,它仍然不会100%确定,但它可能已经足够好了.
$ rar.exe l somefile.zip
somefile.zip is not RAR archive
Run Code Online (Sandbox Code Playgroud)
但即使是WinRAR也会将非RAR文件检测为SFX存档:
$ rar.exe l somefile.srr
SFX Volume somefile.srr
Run Code Online (Sandbox Code Playgroud)
Wil*_*ilt 33
可以在互联网号码分配机构(IANA)上找到正式的哑剧类型列表.根据他们的列表Content-Type标题zip是application/zip.
rar文件的媒体类型未在IANA正式注册,但非官方常用的mime类型值为application/x-rar-compressed.
application/octet-stream意味着:"我发送给你一个文件流,并没有指定这个流的内容"(所以它也可以是一个zip或rar文件).服务器应该检测流的实际内容是什么.
注意:对于上传,依赖Content-Type标题中设置的mime类型是不安全的.标头在客户端上设置,可以设置为任意随机值.相反,您可以使用php文件信息功能来检测服务器上的文件mime-type.
如果您想要下载zip文件而不是其他任何内容,则只应设置一个Accept标头值.如果服务器无法满足您在Accept标头请求的mime-type 中的要求,则将设置任何其他值作为后备.
根据WC3的规格:
application/zip, application/octet-stream
Run Code Online (Sandbox Code Playgroud)
将被定义为:"我更喜欢application/zipmime类型,但如果你不能提供这个application/octet-stream(文件流)也很好".
所以只有一个:
application/zip
Run Code Online (Sandbox Code Playgroud)
将保证您的zip文件(或406 - Not Acceptable服务器无法满足您的请求时的响应).
您不应该信任$_FILES['upfile']['mime'],自己检查MIME类型。为此,您可以使用fileinfoextension,从PHP 5.3.0开始默认启用。
$fileInfo = new finfo(FILEINFO_MIME_TYPE);
$fileMime = $fileInfo->file($_FILES['upfile']['tmp_name']);
$validMimes = array(
'zip' => 'application/zip',
'rar' => 'application/x-rar',
);
$fileExt = array_search($fileMime, $validMimes, true);
if($fileExt != 'zip' && $fileExt != 'rar')
throw new RuntimeException('Invalid file format.');
Run Code Online (Sandbox Code Playgroud)
注意:不要忘记在您php.ini的服务器中启用扩展并重新启动服务器:
extension=php_fileinfo.dll
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
215050 次 |
| 最近记录: |