首页 > PHP > PHP中file_get_contents函数超时的几种解决方法

PHP中file_get_contents函数超时的几种解决方法

2009年07月01号
查看评论 发表评论 542次浏览

在使用file_get_contents函数的时候,经常会出现超时的情况,在这里要通过查看一下错误提示,看看是哪种错误,比较常见的是读取超时,这种情况大家可以通过一些方法来尽量的避免或者解决。这里就简单介绍两种:

一、增加超时的时间限制

这里需要注意: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);
二、一次有延时的话那就多试几次

有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失败将返回 FALSE,所以可以下面这样编写代码:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents(‘http…’))===FALSE) $cnt++;

类别PHP 标签
  1. 匿名
    发表于 2009年07月22号 15时00分21秒 | 1楼

    还不错

  2. 匿名
    发表于 2009年07月22号 15时00分46秒 | 2楼

    还不错,可以试试看

  3. timberland mens boots
    发表于 2010年06月13号 16时22分16秒 | 3楼

    Thank you for the article!

  4. kobe iv
    发表于 2010年06月26号 21时48分22秒 | 4楼

    How perfect! Beautiful advice!

  5. miu miu handbags
    发表于 2010年06月27号 01时02分24秒 | 5楼

    Beautiful story as usual and amazingly true, thank you for that! You are one of a kind.

  6. guess bag online
    发表于 2010年06月27号 15时59分41秒 | 6楼

    I believe sharing is a blessing. So thanks for sharing the free web works.

  7. cheap christian louboutin
    发表于 2010年07月20号 09时36分33秒 | 7楼

    Congratulations on your quest, sounds like it brough you back wonderful memories.

你必需 登陆 才能发表评论.