What is the best way to determine whether or not a

2019-02-26 01:54发布

I have a sever which people can upload files to. The problem is that some of the filenames are mangled (dont have any extension) and so I cannot immediately determine file type. This question is two part: for the files which do have filenames what is the best way to determine whether or not it is an image? (Just a big long if/else if list?) Secondly, for the files which dont have extensions, how can I determine if they are images?

12条回答
放我归山
2楼-- · 2019-02-26 02:17

Look at image magic identify. http://www.imagemagick.org/script/identify.php

The php wrapper is here: http://www.php.net/manual/en/function.imagick-identifyimage.php

Or if you just want to validate that it's an image (and don't care about the meta data): http://www.php.net/manual/en/function.imagick-valid.php

查看更多
放我归山
3楼-- · 2019-02-26 02:23

Try looking at exif_imagetype

查看更多
ゆ 、 Hurt°
4楼-- · 2019-02-26 02:25

You can try to load the image into PHP's GD library, and see if it works.

$file = file_get_contents('file');
$img = imagecreatefromstring($file);
if($img === FALSE){
  // file is NOT an image
}
else{
  // file IS an image
}
查看更多
家丑人穷心不美
5楼-- · 2019-02-26 02:27

If you need a fast solution, use imagesx() and imagesy(). There is also a fast way to check large image file dimensions, by reading just a small amount of data from the file header. Explained in more detail in the following url:

http://hungred.com/useful-information/php-fastest-image-width-height/

查看更多
劳资没心,怎么记你
6楼-- · 2019-02-26 02:28

The type of the image is typically going to be able to be inferenced from the header information of the file.

查看更多
冷血范
7楼-- · 2019-02-26 02:30

You can use the Fileinfo extension: http://www.php.net/manual/en/function.finfo-file.php

finfo_file() uses magic bytes and does not have to load the whole image into memory. The result is a string with the corresponding MIME type, e.g.:

  • text/html
  • image/gif
  • application/vnd.ms-excel
查看更多
登录 后发表回答