简体   繁体   English

在php中获取文件mime类型的最佳方法

[英]Best way to get file mime type in php

what is the best and msit secure way, to get the mime type of a file? 什么是最好的和msit安全方式,获取文件的mime类型? I already found this: 我已经发现了这个:

http://de3.php.net/manual/de/ref.fileinfo.php http://de3.php.net/manual/de/ref.fileinfo.php

But fileinfo() seems to be easy to manipulate. 但是fileinfo()似乎很容易操作。 Is there a better way, to get the file mime type? 有没有更好的方法来获取文件mime类型? I need it for image files, by the way. 顺便说一句,我需要它用于图像文件。

Here's another way 这是另一种方式

<?php
$info = getimagesize("image.gif");
$type = $info['mime'];
?>

But it would help if you could say exactly what you mean by 'secure' and what kind of manipulation you have in mind. 但是,如果您能够准确地说出“安全”的含义以及您想要的操作方式,那将会有所帮助。

getimagesize() returns mime type also http://php.net/manual/en/function.getimagesize.php getimagesize()返回mime类型也是http://php.net/manual/en/function.getimagesize.php

<?php
//png image called gif 
$image = 'temp.gif';
$size = getimagesize($image);

if (isset($size['mime']) && $size[0]>0 && $size[1]>0) {
    echo"Content-type: {$size['mime']}";
    //outputs Content-type: image/png
} else {
     echo"not an image";
}

?>

You can always scan the file yourself for the magic bytes and what-not. 你总是可以自己扫描文件中的魔术字节和什么不是。 There is a bunch of handy funcs in PECL, i believe, but as their availability on the target hosting may way, you may wish to go the hard way. PECL中有一堆方便的功能,我相信,但是由于它们在目标托管上的可用性,你可能希望采取艰难的方式。 See for example this - 看看例如这个 -

http://www.garykessler.net/library/file_sigs.html http://www.garykessler.net/library/file_sigs.html

- for file signatures (or magic bytes, or whatever they are called now). - 用于文件签名(或魔术字节,或现在称为它们的任何内容)。 You know what file types you are going to accept, so just scan the incoming file for the set of the signatures. 您知道要接受哪些文件类型,因此只需扫描传入文件以获取签名集。

Another option is to allow PHP to run the unix shell and use the file command with appropriate flags to test your file and get the true mime-type based on actual file contents. 另一种选择是允许PHP运行unix shell并使用带有适当标志的file命令来测试你的文件,并根据实际的文件内容获得真正的mime类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM