我的网站运行在LAMP环境下,我的图片CDN使用的是nginx。
我想要做的是:检查请求的图片是否有一个副本存储在CDN服务器上,如果有则借用CDN服务器上的副本,否则为用户加载本地副本。
是否有编程方式来检查远程CDN图片是否存在?(也许可以通过判断响应头来确定,因为我注意到如果请求的图片不存在,它会返回404错误)
我使用这种方法来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已经禁用了它。 $content = file_get_contents("path_to_your_remote_img_file");
if ($content === FALSE)
{
/*Load local copy*/
}
else
{
/*Load $content*/
}
还有一件事- 如果您只想使用img标签显示图像,可以简单地使用onerror属性- 如果服务器上不存在该图像,则onerror属性将显示本地文件:
<img src="path_to_your_remote_img_file" onerror='this.src="path_to_your_local_img_file"'>
另一种更简单的方法 - 不需要使用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
}
?>