0

I'm writing test case to image downloading service written in php. We're using phpunit. How can I check if retrieved binary data is an image?

  • possible duplicate of [best way to determine if a URL is an image in PHP](http://stackoverflow.com/questions/676949/best-way-to-determine-if-a-url-is-an-image-in-php) and http://stackoverflow.com/questions/10662915/check-whether-a-file-is-an-image-or-not and http://stackoverflow.com/questions/6391916/is-it-important-to-verify-that-the-uploaded-file-is-an-actual-image-file – Mike B Aug 15 '12 at 12:25
  • `getimagesize()` is the household name for some image formats. Which ones do you need to support? – Pekka Aug 15 '12 at 12:26

1 Answers1

2

Using exif_imagetype (see manual) is nice, but does require you have to the file on your local disk. If you don't mind hard-coding some magic numbers, you could check for the image type directly, see testFetchWithoutSaving in the next example:

class ImageTest extends PHPUnit_Framework_TestCase
{

/**
* @see http://stackoverflow.com/a/676975/841830
*/
public function testFetchWithoutSaving(){
    $s=file_get_contents("https://www.google.com/images/srpr/logo3w.png");
    $this->assertEquals("\x89PNG\x0d\x0a\x1a\x0a",substr($s,0,8));

    $s=file_get_contents("https://www.google.com/");
    $this->assertEquals("\x89PNG\x0d\x0a\x1a\x0a",substr($s,0,8),"Fails: first 8 bytes are actually '<!doctyp'");
    }

/**
* @see http://php.net/manual/en/function.exif-imagetype.php
*/
public function testFetchWithTempFile(){
    $s=file_get_contents("https://www.google.com/images/srpr/logo3w.png");
    $tempFilename="/tmp/phpunit.testImage.testFetchWithTempFile";
    file_put_contents($tempFilename,$s);
    $type=exif_imagetype($tempFilename);
    unlink($tempFilename);
    $this->assertTrue($type!==false);   //Any recognized image type
    $this->assertEquals(IMAGETYPE_PNG,$type);   //A specific image type
    }

}
Darren Cook
  • 27,837
  • 13
  • 117
  • 217