在PHP从远程服务器检索文件时

在PHP从远程服务器检索文件时

本文介绍了在PHP从远程服务器检索文件时,处理延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与PHP一起从远程服务器访问文件和照片。我主要使用的file_get_contents()和复印件()函数。

有时访问一个小的文本文件或照片几乎是一瞬间,但其他时候,它似乎得到卡对同一确切的文件一分钟。有时,它实际上使我的脚本挂了,甚至当我停止脚本阿帕奇保持锁定了几分钟。

我很愿意接受这样的事实,互联网连接可以是片状。我担心的是我恢复正常,而且我不死机​​的Apache - PHP的参数或者set_time_limit()函数只返回一个致命错误。此外,还有PHP手册一张纸条,上面用在流操作时间不利于脚本的运行时间。

我怎样才能从这样的连接问题中恢复,让我的脚本继续吗?而为什么会变成这样造成的Apache挂?

谢谢,布赖恩


解决方案

  $选项=阵列('HTTP'=>阵列(
      USER_AGENT'=> Firefox的崇拜者,
      MAX_REDIRECTS次'=> 1,
      超时=> 10,
  ));
$语境= stream_context_create($选项);
$内容=的file_get_contents($网址,虚假,$背景);

看看和的。以上code将设置连接超时,并允许一个重定向。

这应该prevent到达超时。

的长期拖延可通过网络或通过具有防火墙拒绝您一次或者由路径远程主机上的片状DNS服务器或路由器抢了太多的文件远程服务器引起的。作为一个建议,你应该在本地缓存下载的文件,因此下一次刷新文件将在本地而不是处理的大广网。

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

解决方案
$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 );

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.

这篇关于在PHP从远程服务器检索文件时,处理延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:49