Drill down to the php function file_get_contents timeout handling method

  • 2020-06-07 04:04:09
  • OfStack

1. Increase the timeout limit
Note here: set_time_limit only sets the timeout of your PHP program, not the file_get_contents function that reads the timeout of URL. To really modify the file_get_contents delay, you can use the timeout parameter of resource $context:

$opts = array(  
    'http'=>array(  
        'method'=>"GET",  
        'timeout'=>60,  
    )  );  
$context = stream_context_create($opts);       $html =file_get_contents('http://www.example.com', false, $context); 

2. If there is a delay, try it several times
Sometimes the failure is caused by network and other factors, and there is no solution, but the program can be modified. If it fails, try again several times, but give up after failure, because file_get_contents() will return FALSE if it fails, so the following code can be written:
$cnt=0;
while($cnt < 3 & & ($str=@file_get_contents('http...'))===FALSE) $cnt++;
The above method has timed out OK.
Someone found out that 'method'= > "GET",GET can also be set to post as follows

   function Post($url, $post = null) 
   { 
       $context = array(); 

      if (is_array($post)) { 
          ksort($post); 

           $context['http'] = array ( 
              'timeout'=>60, 
              'method' => 'POST', 
              'content' => http_build_query($post, '', '&'), 
            ); 
      } 

      return file_get_contents($url, false, stream_context_create($context)); 
   } 

   $data = array ( 
       'name' => 'test', 
       'email' => 'test@gmail.com', 
       'submit' => 'submit', 
   ); 

   echo Post('http://www.example.com', $data); 


Related articles: