Search code examples
phpfile-get-contentsphp-ini

if file_get_contents timeout, do something else


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
}

Solution

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