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

查看:33
本文介绍了如何使用 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天全站免登陆