如果不动态指定超时时间,file_get_contents 默认超时时间是受 default_socket_timeout 这个 php.ini 属性影响,也就是60秒,所有 php-fpm 就会被堵塞死。
一、增加超时限制
注意:set_time_limit 只是设置你的PHP程序的超时时间,而不是 file_get_contents 函数读取 URL 的超时时间。
我一开始以为 set_time_limit 也能影响到 file_get_contents,后来经测试是无效的。真正的修改 file_get_contents 延时可以用 resource $context 的 timeout 参数:
- $opts = array(
- 'http'=>array(
- 'method'=>'GET',
- 'timeout'=>60,
- )
- );
- $context = stream_context_create($opts);
- $html = file_get_contents('http://www.example.com', false, $context);
- fpassthru($fp); // 不知道是谁哈?
二、多次尝试
- $cnt = 0;
- while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE)
- {
- $cnt++;
- }
三、POST请求
以上方法对付超时已经OK了。接下来演示一下用 file_get_contents 实现 Post,如下:
- function Post($url, $post = null)
- {
- if (is_array($post))
- {
- ksort($post);
- }
- $context['http'] = array (
- 'method' => 'POST',
- 'timeout' => 60,
- 'content' => http_build_query($post, '', '&'),
- );
- return file_get_contents($url, false, stream_context_create($context));
- }
- $data = array (
- 'name' => 'test',
- 'email' => 'test@gmail.com',
- 'submit' => 'submit',
- );
- echo Post('http://www.example.com', $data);
四、提交Http头
- $context['http'] = array (
- 'method' => 'GET',
- 'header' => "Accept-language: en\r\n" .
- "Cookie: foo=bar\r\n",
- );
- // 注意:Http头每个字段以 \r\n 结尾。
浙公网安备 33010602011771号