PHP: How would you check if the resulting string file_get_contents () is a JPG image?

I use file_get_contents() to pull some images from a remote server, and I want to confirm whether the resulting string is a JPG / PNG image before further processing, for example, save it locally and create thumbs.

 $string = file_get_contents($url); 

How do you do this?

+6
source share
4 answers

You can use getimagesize ()

 $url = 'http://www.geenstijl.nl/archives/images/HassVivaCatFight.jpg'; $file = file_get_contents($url); $tmpfname = tempnam("/tmp", "FOO"); $handle = fopen($tmpfname, "w"); fwrite($handle, $file); $size = getimagesize($tmpfname); if(($size['mime'] == 'image/png') || ($size['mime'] == 'image/jpeg')){ //do something with the $file echo 'yes an jpeg of png'; } else{ echo 'Not an jpeg of png ' . $tmpfname .' '. $size['mime']; fclose($handle); } 

I just tested it to make it work. You need to create a temporary file because the image functions work with local data, and they only accept the path to the local directory, for example, "C: \ wamp2 \ www \ temp \ image.png"

If you do not use fclose($handle); , PHP will automatically remove tmp after the script completes.

+3
source

you can use

exif_imagetype ()

to rate your file. Please check the php manual.

Edited by:

Please note that PHP_EXIF must be enabled. You can learn more about it here.

+2
source

I got the start bits for the jpg image from this. So basically you can check if the start bits are equal or not:

 $url = 'http://i.stack.imgur.com/Jh3mC.jpg?s=128&g=1'; $jpg = file_get_contents($url); if(substr($jpg,0,3) === "\xFF\xD8\xFF"){ echo "It a jpg !"; } 
+2
source

Maybe the standard PHP function exif_imagetype () http://www.php.net/manual/en/function.exif-imagetype.php

+1
source

All Articles