开发者

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? I already found this:

http://de3.php.net/manual/de/ref.fileinfo.ph开发者_开发百科p

But fileinfo() seems to be easy to manipulate. Is there a better way, to get the file mime type? 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

<?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. See for example this -

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜