我所能找到的最好的if
fclose
fopen
类型的东西,使页面加载非常慢。
基本上,我想要做的是:我有一个网站列表,我想在它们旁边显示它们的图标。但是,如果一个站点没有,我想用另一个图像替换它,而不是显示一个损坏的图像。
发布于 2009-06-11 16:08:53
您可以通过CURLOPT_NOBODY指示curl使用HTTP HEAD方法。
大体上
$ch = curl_init("http://www.example.com/favicon.ico");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode >= 400 -> not found, $retcode = 200, found.
curl_close($ch);
无论如何,您只节省了HTTP传输的成本,而不是TCP连接的建立和关闭。由于图标很小,你可能看不到太多的改进。
如果结果被证明太慢,在本地缓存结果似乎是一个好主意。HEAD检查文件的时间,并在headers中返回。你可以像浏览器一样获取图标的CURLINFO_FILETIME。在你的缓存中,你可以存储URL,=>时间戳。然后,您可以比较时间戳并重新加载图标。
发布于 2009-06-11 16:12:26
正如派所说,你可以使用cURL。你可以让cURL只给你头部,而不是主体,这可能会让它更快。坏的域总是需要一段时间,因为您将等待请求超时;您可能可以使用cURL更改超时长度。
下面是一个例子:
function remoteFileExists($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
echo 'file exists';
} else {
echo 'file does not exist';
}
发布于 2010-01-23 07:00:27
CoolGoose的解决方案很好,但对于大文件来说速度更快(因为它只尝试读取1个字节):
if (false === file_get_contents("http://example.com/path/to/image",0,null,0,1)) {
$image = $default_image;
}
https://stackoverflow.com/questions/981954
复制相似问题