Home > Backend Development > PHP Tutorial > How to set the PHP file_get_contents timeout

How to set the PHP file_get_contents timeout

WBOY
Release: 2016-07-25 08:56:17
Original
1028 people have browsed it
  1. $opts = array(

  2. 'http'=>array(
  3. 'method'=>"GET",
  4. 'timeout'=>1,/ /Unit second
  5. )
  6. );

  7. $cnt=0;

  8. while($cnt<3 && ($bb=file_get_contents("http://bbs.it-home.org" , false, stream_context_create($opts)))===FALSE) $cnt++;
  9. echo $cnt;
  10. echo $bb;

Copy code

2. If there is a delay, then Just try a few more times Sometimes the failure is caused by network and other factors. You can modify the program to retry several times when it fails, and then give up if it still fails, because file_get_contents() will return FALSE if it fails. For example: $cnt=0; while($cnt"GET", can it be set to post? For example:

  1. function Post($url, $post = null){

  2. $context = array ();
  3. if (is_array ( $post )) {
  4. ksort ( $ post );
  5. $context ['http'] = array (
  6. 'timeout' => 60,
  7. 'method' => 'POST',
  8. 'content' => http_build_query( $post, '', ' &' )
  9. );

  10. }

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

  13. $data = array (

  14. 'name' => 'test',
  15. 'email' => 'admin@admin.com',
  16. 'submit' => 'submit',
  17. );
  18. echo Post ( 'http://bbs .it-home.org', $data );

Copy the code

That’s it. The above function is still good, and it also solves the problems of timeout control and Post value transfer.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template