简体   繁体   中英

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.php

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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