about the high-level usage of file_get_contents, first of all solve the file_get_contents timeout problem, after the time-out error, like JS in the settimeout like a try, Error more than 3 or 5 times after the confirmation is unable to connect the server and completely give up.
Here's a quick introduction to two workarounds:
One, increase the time limit for timeouts
Note: Set_time_limit only sets the time-out for your PHP program, not the time-out for the file_get_contents function to read the URL.
At first I thought set_time_limit could also affect File_get_contents, which was later tested to be ineffective. The real modification file_get_contents delay can be used with the timeout parameter of the resource $context:
The PHP program code is as follows:
$opts = Array (' http ' =>array ( ' method ' = ' = ' GET ', ' timeout ' =>60, )); $context = Stream_ Context_create ($opts); $html =file_get_contents (' http://www.php.cn ', false, $context); Fpassthru ($FP);
Second, several attempts
The PHP program code is as follows:
$cnt =0;while ($cnt < 3 && ($str = @file_get_contents (' http ... ') ===false) { $cnt + +;}
The above method against timeout is OK. The following is a demonstration of using file_get_contents to implement post, as follows:
PHP program code
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.php.cn ', $data);
Note the set_time_out of the document header or the entire document is timed out.
Related recommendations:
A detailed explanation of the differences between PHP fopen () and file_get_contents ()
Examples of curl in PHP that are better than file_get_contents ()
10 Articles recommended for file_get_contents