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

php

Solution

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.

Problem

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?

Original source

Related problems