加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP file_get_contents忽略超时?

发布时间:2020-12-13 13:57:06 所属栏目:PHP教程 来源:网络整理
导读:$url = 'http://a.url/i-know-is-down';//ini_set('default_socket_timeout',5);$ctx = stream_context_create(array( 'http' = array( 'timeout' = 5,'ignore_errors' = true ) ));$start = microtime(true);$content = @file_get_contents($url,false,$ctx
$url = 'http://a.url/i-know-is-down';

//ini_set('default_socket_timeout',5);

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 5,'ignore_errors' => true
        )
    )
);

$start = microtime(true);
$content = @file_get_contents($url,false,$ctx);
$end = microtime(true);
echo $end - $start,"n";

我得到的回复一般是21.232 segs,不应该是大约五秒钟

取消注释ini_set行根本没有帮助.

您正在使用socket_create_context设置读取超时.如果您尝试访问的页面不存在,则服务器将允许您连接并给您一个404.但是,如果该站点不存在(将不会解析或没有Web服务器在后面),那么file_get_contents( )将忽略读取超时,因为它甚至没有超时连接到它.

我不认为你可以在file_get_contents中设置连接超时.我最近重写了一些代码来使用fsockopen(),正是因为它允许你指定connect timeout

$connTimeout = 30 ;
$fp = fsockopen($hostname,$port,$errno,$errstr,$connTimeout);

那么去fsockopen的方法需要你再循环一遍fread(),稍微复制你的代码.但是,当您使用stream_get_meta_data()读取时,会检测到读取超时,

http://php.net/stream_get_meta_data

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读