file_get_contents超时问题及解决方案

WBOY
Release: 2016-05-19 12:16:06
Original
1172 people have browsed it

经常会使用php中的file_get_contents()函数去抓取远程页面, 对方页面文件过大、对方页面反应时间太久或网络传输慢等原因都可能会导致file_get_contents()执行时间超过php的最大执行时间。而一 旦file_get_contents出错即会终止整个程序。

测试用例


Copy after login

上面代码首先将php的最大执行时间设置为2秒,然后去远程读取170KB的文件,按照本人的网络环境下载170KB文件需时超过1s.

现象

Fatal error: Maximum execution time of 2 second exceeded in C:\wamp\www\phptest\timeout.php on line 4

这是由网络造成的php执行超时,在file_get_contents超时时即报错并且程序停止执行。而基本上大多数需求是即使发生错误也要求程序继续向下执行。

解决办法

Copy after login
 
Copy after login

现象

bool(false)

成功解决了超时导致程序不能继续执行的问题。

这里需要注意的是,设置curl的CURLOPT_TIMEOUT的值应该小于php最大执行时间。

为什么要说应该而不是必须?用两个例子对比来说明,假设抓取页面需4s。

example 1
max_execution_time 为 2
CURLOPT_TIMEOUT 为 3

example 2
max_execution_time 为 10
CURLOPT_TIMEOUT 为 20

我对这个过程的理解是,php监控整个脚本的时间,curl监控抓取页面的时间。对例1, 抓取远程页面的过程中已经达到php最大执行时间,得到的结果和file_get_contents一样。
例2中,整个脚本的执行时间不到5s, 所以不受设定时间的限制.

 
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!