9

I am using file_get_contents() to pull some images from a remote server and I want to confirm if the result string is a JPG/PNG image before further processing, like saving it locally and create thumbs.

$string = file_get_contents($url);

How would you do this?

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Bertrand
  • 13,540
  • 5
  • 39
  • 48
  • What about this? http://stackoverflow.com/questions/1141227/php-checking-if-the-images-is-jpg – George Mar 22 '13 at 14:11

4 Answers4

6

I got from this answer the starting bits for a JPG image. So basically what you could do is to check whether the starting bits are equal or not:

$url = 'https://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's a jpg !";
}
Community
  • 1
  • 1
HamZa
  • 14,671
  • 11
  • 54
  • 75
  • 1
    This is the best answer to this question IMO since it doesn't require a temp file strategy or installed extensions. – jwhazel Mar 01 '17 at 18:29
5

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 so it works. You need to make a temp file becouse the image functions work with local data and they only accept local directory path like 'C:\wamp2\www\temp\image.png'

If you do not use fclose($handle); PHP will automatically delete tmp after script ended.

botenvouwer
  • 4,334
  • 9
  • 46
  • 75
3

You can use

exif_imagetype()

to evaluate your file. Please do check the php manual.

Edited :

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

Moch. Rasyid
  • 366
  • 5
  • 16
1

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

Vitmais
  • 33
  • 3