检查远程镜像是否存在 PHP


Check if remote images exist PHP

我正在使用 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 检查 HTTP 响应代码 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);
function fileExists($path){
    return (@fopen($path,"r")==true);
}

来自 file_exists() 的手册

根据图像的数量和失败的频率,最好坚持使用当前的客户端方法。此外,看起来图像是通过 Amazon CloudFront 提供的 - 在这种情况下,请使用客户端方法,因为它可能只是单个边缘服务器的传播问题。

应用服务器端方法将是网络密集型和缓慢的(浪费资源),尤其是在 php 中,因为您需要按顺序检查每个图像。

使用 php 函数检查请求标头也可能很有用get_headers如下所示:

$url = "http://www.remoteserver.com/image.jpg";
$imgHeaders = @get_headers( str_replace(" ", "%20", $url) )[0];
if( $imgHeaders == 'HTTP/1.1 200 Ok' ) {
    //img exist
}
elseif( $imgHeaders == 'HTTP/1.1 404 Not Found' ) {
    //img doesn't exist
}

以下函数将尝试使用get_headers获取URL给出的任何在线资源(IMG,PDF等),读取标头并使用函数strpos在其中搜索字符串"未找到"。如果找到此字符串,则表示 URL 提供的资源不可用,则此函数将返回 FALSE,否则返回 TRUE。

function isResourceAvaiable($url)
{
  return !strpos(@get_headers($url)[0],'Not Found')>0;
}