PHP - 设置的file_get_contents超时 [英] PHP - Setting a file_get_contents timeout

查看:214
本文介绍了PHP - 设置的file_get_contents超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的file_get_contents 来获取外部页面的标题,以确定外部页面在线像这样:

  $ URL =HTTP://page.location/
$语境= stream_context_create(阵列(
'HTTP'=>阵列(
    '方法'= GT; '得到',

));
的file_get_contents($网址,虚假,$背景);
$ responseHeaders响应= $ http_response_header;$头= SUBSTR($ responseHeaders响应[0],9,3);如果($头[0] ==5|| $头[0] ==4){
//做东西
}

这是当页面太长回应,除了运作良好。

如何设置超时?

威尔 file_get_headers 收益 FALSE 如果还没有完成,将PHP移到下一行,如果还没有完成的file_get_contents 请求?


解决方案

添加暂停键中的 stream_context_array

  $语境= stream_context_create(阵列(
'HTTP'=>阵列(
    '方法'= GT; '得到',
    超时=> 30,//< ----这里(即以秒为单位)

));


您的问题....


  

将file_get_headers返回FALSE,如果它尚未完成和
  PHP将移到下一行,如果还没有完成
  的file_get_contents请求?


,将一起返回FALSE与如下面的警告信息。


  

一个连接尝试失败,因为连接的方没有
  在一段时间后作出适当的反应,或已建立的连接
  失败,因为连接的主机没有反应。


I am using file_get_contents to get a headers of an external page to determine if the external page is online like so:

$URL = "http://page.location/";
$Context = stream_context_create(array(
'http' => array(
    'method' => 'GET',
)
));
file_get_contents($URL, false, $Context);
$ResponseHeaders = $http_response_header;

$header = substr($ResponseHeaders[0], 9, 3);

if($header[0] == "5" || $header[0] == "4"){
//do stuff
}

This is working well except when the page is taking too long to respond.

How do I set a timeout?

Will file_get_headers return FALSE if it has not completed yet and will PHP move to the next line if it has not completed the file_get_contents request?

解决方案

Add a timeout key inside the stream_context_array

$Context = stream_context_create(array(
'http' => array(
    'method' => 'GET',
    'timeout' => 30, //<---- Here (That is in seconds)
)
));


Your Question....

will file_get_headers return FALSE if it has not completed yet and will PHP move to the next line if it has not completed the file_get_contents request?

Yes , it will return FALSE along with the below warning message as shown.

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

这篇关于PHP - 设置的file_get_contents超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆