Search code examples
phplinuximagemime-typesfile-type

Find if file data is an image (php)


Imagine I have some file data in a variable $data. I need to determine whether it is an image or not. No need for details such as corrupt images etc.

First thought would be getting the file mime type by looking at the magic number and then see whether "image" is in the mime type.

No such luck, even if I have a "file extension to mime type" script, I don't have a reliable way to get mime from magic number.

My next option was to have a reasonable list of image file magic numbers and consult them. However, it is relatively difficult to find such magic numbers (gif for instance has different magic numbers, some of which could pretty rare - if memory serves me right).

A better idea would be some linux program which can do this kind of thing.

Any ideas? I'm running RHEL and PHP 5.3. I've got root access - ie able to install stuff if needed.

- Chris.


Solution

  • The best answer (which I've determined from Col. Shrapnel) would be the use of:

    $handle = imagecreatefromstring($data);
    

    Quoting the PHP manual:

    An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.