Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether image exists on remote URL

Tags:

url

php

curl

image

I am generating dynamic URLs of images for book ISBNs. I need a reliable way with PHP to check whether the images actually exist at the remote url. I tried various approaches with different PHP libraries, curl, etc., but none of them works well, some of them are downright slow. Given the fact that I need to generate (and check!) about 60 URLS for each book in my database, this is a huge waiting time. Any clues?

like image 815
Cristian Cotovan Avatar asked Sep 01 '09 18:09

Cristian Cotovan


4 Answers

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);

    $result = curl_exec($ch);
    curl_close($ch);
    if($result !== FALSE)
    {
        return true;
    }
    else
    {
        return false;
    }
}

--> that is the fastest way if your host supports curl

like image 56
dangkhoaweb Avatar answered Nov 06 '22 02:11

dangkhoaweb


Use getimagesize() method like this

$external_link = ‘http://www.example.com/example.jpg’;
if (@getimagesize($external_link)) {
echo  “image exists “;
} else {
echo  “image does not exist “;
}
like image 42
mohsin139 Avatar answered Nov 06 '22 03:11

mohsin139


There is no "easy" way here - at a very minimum, you need to generate a HEAD request and check the resulting content type to make sure it's an image. That's not taking into account possible referrer issues. curl is the way to go here.

like image 6
ChssPly76 Avatar answered Nov 06 '22 04:11

ChssPly76


You could use curl. Just set the curl option CURLOPT_NOBODY to true. This will skip body information and only get the head (thus http code as well). Then, you could use the CURLOPT_FAILONERROR to turn this whole process into a true/false type check

like image 4
Kevin Peno Avatar answered Nov 06 '22 02:11

Kevin Peno