How to check Url Image is exist or not in php

Mark Martin picture Mark Martin · Mar 18, 2013 · Viewed 11.9k times · Source

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...

Answer

Dead Man picture Dead Man · Mar 18, 2013

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