1

I have a piece of code for file_get_contents and it works fine, but sometimes the source URL does not respond and because of that my page does not load for 60 seconds (after default timeout). I want to set 5 seconds timeout for file_get_contents to do something else if the source URL does not respond in 5 seconds. this is my code:

  <?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>'
};
?>

I want something like this after above code:

if source url dose not respond in 5 seconds
{
do something else
}
  • Does this answer your question? [Does file\_get\_contents() have a timeout setting?](https://stackoverflow.com/questions/10236166/does-file-get-contents-have-a-timeout-setting) – Mech Mar 30 '20 at 22:09
  • Please select an answer to help users with the same issue find the solution. – Mech Mar 31 '20 at 16:09

2 Answers2

0

This is what you are looking for:

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

src: Does file_get_contents() have a timeout setting?

Flagging question as duplicate for removal.

Mech
  • 3,952
  • 2
  • 14
  • 25
0

My Answer: I saw this topic before Does file_get_contents() have a timeout setting? but it wasn't exactly what I want. I wanted to do something else if the timeout happens. so I used this code:

$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'
}