检查PHP是否存在远程映像 [英] Check if remote images exist PHP

查看:160
本文介绍了检查PHP是否存在远程映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用last.fm API来获取最近的曲目以及搜索专辑和艺术家等。
从API返回图像时,它们有时不存在。一个空的URL字符串很容易被占位符图像替换,但是当给出一个图像URL并且它返回404时,就是我的问题出现时。

I'm using the last.fm API to get the recent tracks and to search albums and artists etc. When images are returned from the API, they sometimes doesn't exist. An empty URL string is easily replaced with a placeholder image, but when an image url is given and it returns a 404, that's when my problem comes in.

我试过使用fopen($ url,'r')用于检查图像是否可用,但有时会出现以下错误:

I tried using fopen($url, 'r') for checking if images are available, but sometimes this gives me the following error:

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,因为有很多图像要检查,它会使网站大量减速。

Also, I don't want to use cURL, because there are a lot of images to check and it slows the website down a lot.

检查图像的最佳解决方案是什么?
我现在使用以下解决方案:

What would the best solution be for checking images? I'm now using the following solution:

 <img src="..." onerror='this.src="core/img/no-image.jpg"' alt="..." title="..." /> 

这有用吗?

任何帮助赞赏

推荐答案

您可以使用 getimagesize ,因为您正在处理图像它还会返回图像的mime类型

You can use getimagesize since you are dealing with images it would also return mime type of the image

   $imageInfo = @getimagesize("http://www.remoteserver.com/image.jpg");

您还可以使用CURL检查am image的HTTP响应代码或任何网址

You can also use CURL to check HTTP response code of am image or any 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是否存在远程映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆