如果file_get_contents超时,请执行其他操作

时间:2020-03-30 22:05:38

标签: php file-get-contents php-ini

我有一段file_get_contents的代码,它可以正常工作,但是有时源URL无法响应,因此我的页面在60秒内(默认超时后)不会加载。 如果源URL在5秒内没有响应,我想为file_get_contents设置5秒超时以执行其他操作。 这是我的代码:

  <?php 
$url = 'https://www.example.com';
$content = file_get_contents($url);
$first_step = explode( '<div class="js-price-value">' , $content );
$second_step = explode("</div>" , $first_step[1] );
$second_step[0]= str_replace( " ", "",  $second_step[0]);
if (strlen(trim($second_step[0]))!==0) {
 $price=$second_step[0];

 echo $price;  

}else {
   echo '<div>something else</div>'
};
?>

在上面的代码之后,我想要这样的东西:

if source url dose not respond in 5 seconds
{
do something else
}

2 个答案:

答案 0 :(得分:0)

这是您要寻找的:

file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));

src:Does file_get_contents() have a timeout setting?

标记问题重复删除。

答案 1 :(得分:0)

我的答案: 我以前看过这个话题 Does file_get_contents() have a timeout setting? 但这不是我想要的。如果发生超时,我想做其他事情。 所以我使用了这段代码:

$ctx = stream_context_create(array(
   'http' => array(
       'timeout' => 5
       )
   )
);
$url = 'source URL';
$content = file_get_contents("$url", 0, $ctx);
if(!$content){
   echo 'timeout happened';

}elseif (another condition) {
   echo 'condition result'

}else {
   echo 'something else'
}