php check if remote image cant be displayed

96 views Asked by At

I have a script that gets images from an external website and display it on mine. I need to show a different image if the external image is 404 or can't be displayed. I tried various approaches but couldnt find anything that works :(

This is an example of an image that cant be displayed on the remote server (it show a text error instead of displaying an image) http://image.spreadshirtmedia.com/image-server/v1/compositions/1112876576765766798/views/1,width=1000,height=1000,appearanceId=95/

And here's my code

$path = "http://image.spreadshirtmedia.com/image-server/v1/compositions/111286798/views/1,width=1000,height=1000,appearanceId=95/t.jpg";

// Load the requested image
$image = imagecreatefromstring(file_get_contents($path.'?'.mt_rand()));

// Send the image
header('Content-type: image/png');


function get_http_response_code($path) {
    $headers = get_headers($path);
    return substr($headers[0], 9, 3);
}
if(get_http_response_code($path) != "404"){
    imagepng($image);
}else{
    imagepng("notfound.png");
}
1

There are 1 answers

1
Kiran Dash On

I can instruct curl to solve your problem:

CODE EXAMPLE:

$curlIni = curl_init("http://image.spreadshirtmedia.com/image-server/v1/compositions/111286798/views/1,width=1000,height=1000,appearanceId=95/t.jpg");

curl_setopt($curlIni, CURLOPT_NOBODY, true);
curl_exec($curlIni);
$returnCode = curl_getinfo($curlIni, CURLINFO_HTTP_CODE);
// $returnCode >= 400 -> not found, $returnCode = 200, found.
curl_close($curlIni);