Validate that a file is a picture in PHP

2019-01-19 12:34发布

问题:

If a file is uploaded to the server, is there a way using PHP, to make sure that it's actually a picture and not just a file with a .jpg or .gif extension?

回答1:

Using (part) of the GD library.

PHP: GD - Manual

array getimagesize ( string $filename [, array &$imageinfo ] )

The first element of the array will be 0 if there is no image. PHP: getimagesize

If you don't have GD installed (most of the time you will), you can read the file header as Shane mentioned.

EDIT: Actually, as Neal pointed out in the comments, the GD library is not even required to use this function. So use it.



回答2:

best way to check if file is an image

function is_image($path)
{
    $a = getimagesize($path);
    $image_type = $a[2];

    if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP)))
    {
        return true;
    }
    return false;
}

more: http://www.binarytides.com/php-check-if-file-is-an-image/



回答3:

The most efficient way would be to look at the beginning bytes of the file and test for 'magic number' file specifier. Here is a list of magic numbers.



回答4:

For the record: Now in 2013+ we can:

For max. compatibility (If you don't have GD library).
Use the always available mime-content-type ((PHP 4 >= 4.3.0, PHP 5))

$type = mime_content_type($filename);
if (strstr($type, 'image/'))
{
    echo 'is image';
}