What is the best and fastest way to check if the image is valid in PHP?

前端 未结 6 1356
别那么骄傲
别那么骄傲 2021-01-01 11:07

What is the best and fastest way to check if the image is valid in PHP ? I need it to be able to check GIF, JPG as well as PNG images.

6条回答
  •  清歌不尽
    2021-01-01 11:35

    As recommended by the PHP documentation:

    "Do not use getimagesize() to check that a given file is a valid image.Use a purpose-built solution such as the Fileinfo extension instead."

    Here is an example:

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $type = finfo_file($finfo, "test.jpg");
    
    if (isset($type) && in_array($type, array("image/png", "image/jpeg", "image/gif"))) {
        echo 'This is an image file';
    } else {
        echo 'Not an image :(';
    }
    

提交回复
热议问题