且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 PHP 检查远程文件是否存在?

更新时间:2022-06-22 23:58:08

您可以通过 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.