Bertrand
Bertrand

Reputation: 13570

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

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?

Upvotes: 8

Views: 6228

Answers (4)

botenvouwer
botenvouwer

Reputation: 4432

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.

Upvotes: 5

HamZa
HamZa

Reputation: 14921

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.sstatic.net/Jh3mC.jpg?s=128&g=1';
$jpg = file_get_contents($url);

if(substr($jpg,0,3) === "\xFF\xD8\xFF"){
    echo "It's a jpg !";
}

Upvotes: 8

Vitmais
Vitmais

Reputation: 33

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

Upvotes: 1

Moch. Rasyid
Moch. Rasyid

Reputation: 356

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

Upvotes: 2

Related Questions