Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 407
Christian Avatar asked Mar 23 '26 04:03

Christian


2 Answers

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.

like image 161
Christian Avatar answered Mar 24 '26 18:03

Christian


The standard file utility might be what you're looking for. It uses a table of magic numbers to identify the file format:

$ file test.jpg 
test.jpg: JPEG image data, JFIF standard 1.01

If you don't wish to create a temporary file, you can use file - and pipe the data into its stdin. Make sure you watch for the termination of the child process, because file will write its output and stop as soon as it has read enough of your stream to be certain of the format.

like image 39
Greg Hewgill Avatar answered Mar 24 '26 19:03

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!