问题描述
限时送ChatGPT账号..我正在使用 PHP 从远程服务器访问文件和照片.我主要使用 file_get_contents() 和 copy() 函数.
I am working with PHP to access files and photos from remote servers. I am mostly using the file_get_contents() and copy() functions.
有时访问一个小的文本文件或照片几乎是即时的,但有时它似乎在同一个文件上卡住"了一分钟.有时它实际上会导致我的脚本挂起,即使我停止脚本,Apache 仍会锁定几分钟.
Sometimes accessing a small text file or photo is almost instant, but other times it seems to get "stuck" for a minute on the same exact file. And sometimes it actually causes my script to hang, and even when I stop the script Apache remains locked up for several minutes.
我非常愿意接受互联网连接可能不稳定的事实.我担心的是我可以正常恢复并且不会使 Apache 崩溃 - PHP set_time_limit() 函数只返回一个致命错误.另外,PHP 手册中有一个说明,流操作所花费的时间不会影响脚本的运行时间.
I'm quite willing to accept the fact that internet connections can be flaky. My concern is that I recover gracefully and that I do not crash Apache - the PHP set_time_limit() function only returns a fatal error. In addition, there is a note in the PHP manual that time spent on stream operations does not contribute to the running time of the script.
如何从此类连接问题中恢复并允许我的脚本继续运行?为什么这会导致 Apache 挂起?
How can I recover from such connection problems and allow my script to continue? And why would this be causing Apache to hang?
谢谢,布赖恩
推荐答案
$options = array( 'http' => array(
'user_agent' => 'Firefox wannabe',
'max_redirects' => 1,
'timeout' => 10,
) );
$context = stream_context_create( $options );
$content = file_get_contents( $url, false, $context );
看看 stream_context_create
和HTTP 上下文选项.上面的代码将设置连接超时,并允许一次重定向.
Take a look at stream_context_create
and HTTP Context Options. The above code will set a timeout on the connection, and will allow for one redirect.
这应该可以防止超时.
长时间延迟可能是由于网络或远程服务器的防火墙拒绝您一次获取过多文件或远程主机路径上的不稳定 DNS 服务器或路由器造成的.建议您将下载的文件缓存在本地,以便下次刷新文件将在本地处理,而不是大网.
The long delays may be caused by the network or by the remote server having a firewall denying you to grab too many files at once or by a flaky DNS server or router on the path to the remote host. As a suggestion, you should cache locally the downloaded files, so on the next refresh files will be handled locally instead of the big wide net.
这篇关于在 PHP 中从远程服务器检索文件时处理延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论