The example of this article tells the PHP file_get_contents advanced usage, share for everybody reference. The specific analysis is as follows:
First of all, solve the file_get_contents timeout problem, after the timeout return error, like JS in the settimeout as an attempt, error more than 3 times or 5 times after the confirmation as unable to connect the server and completely give up.
Here's a quick overview of two solutions:
One, increase time limit of timeout
Note: Set_time_limit only sets the timeout time for your PHP program, not the timeout for the file_get_contents function to read the URL.
I initially thought Set_time_limit could also affect File_get_contents, which was later tested to be ineffective. The real modification of the file_get_contents delay can be resource $context timeout parameters:
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.jb51.net ', false, $context);
Fpassthru ($FP);
Second, many attempts
The PHP program code is as follows:
$cnt =0;
while ($cnt < 3 && ($str = @file_get_contents (' http ... ')) ===false {
$cnt + +;
}
The above method of dealing with timeout is OK. Next, I'll show you how to implement post with File_get_contents, 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 '
); C17/>echo Post (' http://www.jb51.net ', $data);
Note the set_time_out of the document header or the entire document will be timed out.
I hope this article will help you with the learning of PHP programming.