如何使用PHP检查是否存在远程文件? [英] How can one check to see if a remote file exists using PHP?

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

问题描述

我能找到的最好的if fclose fopen类型的东西使页面加载真的很慢.

The best I could find, an if fclose fopen type thing, makes the page load really slowly.

基本上我想要做的是:我有一个网站列表,我想在它们旁边显示它们的图标.但是,如果一个站点没有站点,我想用另一个图像代替它,而不是显示损坏的图像.

Basically what I'm trying to do is the following: I have a list of websites, and I want to display their favicons next to them. However, if a site doesn't have one, I'd like to replace it with another image rather than display a broken image.

推荐答案

您可以通过CURLOPT_NOBODY指示curl使用HTTP HEAD方法.

You can instruct curl to use the HTTP HEAD method via CURLOPT_NOBODY.

或多或少

$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连接的建立和关闭的成本.而且,将图标设为小图标可能不会带来太大的改善.

Anyway, you only save the cost of the HTTP transfer, not the TCP connection establishment and closing. And being favicons small, you might not see much improvement.

如果结果太慢,则在本地缓存结果似乎是个好主意. HEAD检查文件的时间,并在标题中返回它.您可以像浏览器一样使用并获取图标的CURLINFO_FILETIME. 在缓存中,您可以存储URL => [favicon,timestamp].然后,您可以比较时间戳记并重新加载收藏夹图标.

Caching the result locally seems a good idea if it turns out to be too slow. HEAD checks the time of the file, and returns it in the headers. You can do like browsers and get the CURLINFO_FILETIME of the icon. In your cache you can store the URL => [ favicon, timestamp ]. You can then compare the timestamp and reload the favicon.

这篇关于如何使用PHP检查是否存在远程文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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