1

I am working around fetch image URL from database & show image in php like following

<?php    

$row['blog_url'] = "http://www.nasa.gov/images/content/711375main_grail20121205_4x3_946-710.jpg";

<img src="<?php echo $row['blog_url']; ?>"  height="200" width="200" alt="image"/>

?>

but i want display no_imgae.jpeg if image not getting loaded from specified url as blog_url

if there any way to find out image is exist or not in php

thanks in advance...

Mark Martin
  • 153
  • 2
  • 5
  • 11

3 Answers3

3

This function will solve your problem :

function checkRemoteFile($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    // don't download content
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(curl_exec($ch)!==FALSE)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Just pass the image url in this function and it will return yes if image exists otherwise false

Dead Man
  • 2,880
  • 23
  • 37
1
$file = "http://www.nasa.gov/images/content/711375main_grail20121205_4x3_946-710.jpg";
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}
Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
  • What if it's `HTTP/1.0`? There are better ways to check for this. Also, this _only_ looks at 404s. For the OPs case, it may be important that it's specifically a 200 response. No redirects, no authorization, etc. – Colin M Mar 18 '13 at 12:55
0
<?
$img = $row['blog_url'];
$headers = get_headers($img);
if(substr($headers[0], 9, 3) == '200') {
?>
<img src="<?php echo $img; ?>"/>
<?
} else {
?>
<img src="noimage.jpg"/>
<?
}
?>
Kautil
  • 1,321
  • 9
  • 13
  • Array ( [0] => HTTP/1.0 400 Bad Request [1] => Server: AkamaiGHost [2] => Mime-Version: 1.0 [3] => Content-Type: text/html [4] => Content-Length: 215 [5] => Expires: Mon, 18 Mar 2013 12:58:50 GMT [6] => Date: Mon, 18 Mar 2013 12:58:50 GMT [7] => Connection: close ) – Mark Martin Mar 18 '13 at 13:01