我正在使用 last.fm API 来获取最近的轨道并搜索专辑和艺术家等。 当从 API 返回图像时,它们有时并不存在。空的 URL 字符串很容易被占位符图像替换,但是当给出图像 url 并返回 404 时,这就是我的问题。
我尝试使用 fopen($url, 'r') 检查图像是否可用,但有时会出现以下错误:
Warning: fopen(http://ec1.images-amazon.com/images/I/31II3Cn67jL.jpg) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in file.php on line 371
另外,我不想使用 cURL,因为有很多图像需要检查,而且它会大大降低网站速度。
检查图像的最佳解决方案是什么? 我现在使用以下解决方案:
<img src="..." onerror='this.src="core/img/no-image.jpg"' alt="..." title="..." />
这有用吗?
感谢任何帮助
最佳答案
您可以使用 getimagesize
因为您正在处理图像,它还会返回图像的 mime 类型
$imageInfo = @getimagesize("http://www.remoteserver.com/image.jpg");
您还可以使用 CURL 来检查 am image
或任何 URL
$ch = curl_init("http://www.remoteserver.com/image.jpg");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200)
{
// Found Image
}
curl_close($ch);
关于php - 检查远程图像是否存在 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10489210/