Search code examples
phpimagefile-uploadgetimagesize

PHP check if file is an image


Is there a way to make sure a received file is an image in PHP?

Testing for the extension doesn't sound very secure to me as you could upload a script and change its extension to whatever you want.

I've tried to use getimagesize too, but there might be something more suited for that particular problem.


Solution

  • Native way to get the mimetype:

    For PHP < 5.3 use mime_content_type()
    For PHP >= 5.3 use finfo_open() or mime_content_type()

    Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

    While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

    If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

    function getMimeType($filename)
    {
        $mimetype = false;
        if(function_exists('finfo_open')) {
            // open with FileInfo
        } elseif(function_exists('getimagesize')) {
            // open with GD
        } elseif(function_exists('exif_imagetype')) {
           // open with EXIF
        } elseif(function_exists('mime_content_type')) {
           $mimetype = mime_content_type($filename);
        }
        return $mimetype;
    }