【发布时间】:2012-02-14 02:40:02
【问题描述】:
我的网站在 LAMP 中运行,我的图片 CDN 在 nginx 中。
我想做的是: 检查请求的图像在 CDN 服务器中是否有副本,如果有则将副本借给 CDN 服务器,否则为用户加载本地副本。
是否有以编程方式检查远程 CDN 图像是否存在?
(也许确定标头?因为我注意到如果请求图像不存在,则返回 404)
【问题讨论】:
-
加载是什么意思..你想用
显示图像吗?
我的网站在 LAMP 中运行,我的图片 CDN 在 nginx 中。
我想做的是: 检查请求的图像在 CDN 服务器中是否有副本,如果有则将副本借给 CDN 服务器,否则为用户加载本地副本。
是否有以编程方式检查远程 CDN 图像是否存在?
(也许确定标头?因为我注意到如果请求图像不存在,则返回 404)
【问题讨论】:
只要副本是公开的,您就可以使用 cURL 检查 404。 See this question 详细说明如何操作。
【讨论】:
我用这个方法ping远程文件:
/**
* Use HTTP GET to ping an url
*
* /!\ Warning, the return value is always true, you must use === to test the response type too.
*
* @param string $url
* @return boolean true or the error message
*/
public static function pingDistantFile($url)
{
$options = array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_URL => $url,
CURLOPT_FAILONERROR => true, // HTTP code > 400 will throw curl error
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$return = curl_exec($ch);
if ($return === false)
{
return curl_error($ch);
}
else
{
return true;
}
}
您也可以使用 HEAD 方法,但可能您的 CDN 已禁用它。
【讨论】:
您可以为此使用 file_get_contents:
$content = file_get_contents("path_to_your_remote_img_file");
if ($content === FALSE)
{
/*Load local copy*/
}
else
{
/*Load $content*/
}
还有一件事——如果你只想显示带有 img 标签的图像,你可以简单地这样做——使用 img 标签 onerror 属性——如果图像在服务器上不存在,onerror 属性将显示本地文件:
<img src="path_to_your_remote_img_file" onerror='this.src="path_to_your_local_img_file"'>
您可以在此处阅读类似的问题:detect broken image using php
【讨论】:
另一种更简单的方法 - 没有 cURL:
$headers = get_headers('http://example.com/image.jpg', 1);
if($headers[0] == 'HTTP/1.1 200 OK')
{
//image exist
}
else
{
//some kind of error
}
【讨论】:
<?php
if (is_array(getimagesize("http://www.imagelocation.com/image.png"))){
// Image ok
} else {
// Image not ok
}
?>
【讨论】: