What is the best way to determine whether or not a file is an image in PHP?

前端 未结 12 483
有刺的猬
有刺的猬 2021-01-22 07:25

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.

相关标签:
12条回答
  • 2021-01-22 07:40

    You can use getimagesize It does not require the GD image library and it returns same information about image type. http://it2.php.net/manual/en/function.getimagesize.php

    0 讨论(0)
  • 2021-01-22 07:41

    Try looking at exif_imagetype

    0 讨论(0)
  • 2021-01-22 07:45

    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
    }
    
    0 讨论(0)
  • 2021-01-22 07:46

    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
    0 讨论(0)
  • 2021-01-22 07:47

    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

    0 讨论(0)
  • 2021-01-22 07:57

    If you have the GD2 extension enabled, you could just use that to load the file as an image, then if it returns invalid you can catch the error and return FALSE, otherwise return TRUE.

    0 讨论(0)
提交回复
热议问题