在 PHP 中从远程服务器检索文件时处理延迟
我正在使用 PHP 来访问远程服务器上的文件和照片。我主要使用 file_get_contents() 和 copy() 函数。
有时访问一个小文本文件或照片几乎是即时的,但有时它似乎会在同一个文件上“卡住”一分钟。有时它实际上会导致我的脚本挂起,即使我停止脚本,Apache 仍会锁定几分钟。
我非常愿意接受互联网连接可能不稳定的事实。我担心的是我可以正常恢复并且不会使 Apache 崩溃 - PHP set_time_limit() 函数仅返回致命错误。另外,PHP手册中有一条注释,流操作所花费的时间不会影响脚本的运行时间。
如何从此类连接问题中恢复并允许我的脚本继续运行?为什么这会导致 Apache 挂起?
谢谢,布莱恩
I am working with PHP to access files and photos from remote servers. I am mostly using the file_get_contents() and copy() functions.
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.
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.
How can I recover from such connection problems and allow my script to continue? And why would this be causing Apache to hang?
Thanks, Brian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看
stream_context_create
和 HTTP 上下文选项。上面的代码将设置连接超时,并允许一次重定向。这应该可以防止超时。
长时间的延迟可能是由网络或具有防火墙的远程服务器(拒绝您一次获取太多文件)或远程主机路径上不稳定的 DNS 服务器或路由器引起的。建议您在本地缓存下载的文件,以便下次刷新时文件将在本地处理,而不是在大范围的网络上处理。
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.This should prevent reaching the timeout.
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.