Search code examples
phpphp-curl

How to check whether a web page contains an image file using PHP?


I have this code to check whether a file exist in a web page. The code is working fine as long as the file exists. If the file doesn't exist, an error message is to be displayed, but it's not showing. Any help, please?

<?
$ch = curl_init("https://en.wikipedia.org/wiki/File:Ash_Tree_-_geograph.org.uk_-_590711.jpg");

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

if($retcode == 200)
{
echo "Found";
}
elseif($retcode == 400)
{
echo "Error";
}
?>



Solution

  • If the file doesn't exists, the returned http status should be 404.

    ...
    400 Bad Request 
    401 Unauthorized
    402 Payment Required
    403 Forbidden
    404 Not Found
    ...
    

    List of all codes: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

    So for checking strictly this condition (file not found), your code should be:

    if ($retcode == 200)
    {
        echo "Found";
    }
    elseif ($retcode == 404)
    {
        echo "Error";
    }