hkguile
hkguile

Reputation: 4369

php ensure file_get_contents images not corrput

I have a php script to use file_get_contents to download remote images to server, but sometime it is corrupted

$contents = file_get_contents($url);
list($width,$height) = getimagesizefromstring( $contents );

if($width <= 300 ){
    $contents = base64_decode('isdfafasfgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=');
    $downloadlog->log( "ignore file width below 300 : " . $url );
}

$aws->writeToAWS( $target_path , $contents );
$contents = null; 

Are there any ways to ensure the images are downloaded correctly without any corruption or a way to validate the images against remote url?

Upvotes: 0

Views: 436

Answers (1)

Jacob Goh
Jacob Goh

Reputation: 20845

You can validate using getimagesize

Note: Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

On failure, FALSE is returned.


edited:

for example

<?php
$array = getimagesize('https://dl.dropboxusercontent.com/u/22492671/not_an_image.jpg');
if( $array ){
    echo '<pre>';
    print_r($array);
    echo '</pre>';
} else {
    echo 'image broken';
}
?>

getimagesize() return false when image is broken.

Upvotes: 1

Related Questions