如何使用PHP检查网页是否包含图像文件?

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

我有这段代码可以检查网页中是否存在文件。只要文件存在,代码就可以正常工作。如果该文件不存在,将显示一条错误消息,但它没有显示。 有什么帮助吗?

<?
$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";
}
?>


如果文件不存在,返回的http状态应该是404

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

所有代码列表: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

因此,为了严格检查此条件(未找到文件),您的代码应为:

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