This article mainly introduces file_get_contents high-latency usage in PHP, including timeout restrictions and POST implementation usage. For more information, see the following example to describe file_get_contents advanced usage in PHP, share it with you for your reference. The specific analysis is as follows:
First, solve the problem of file_get_contents timeout. After a timeout error is returned, an attempt is made like settimeout in js. after the error is returned three or five times, the attempt is confirmed to be unable to connect to the server and the attempt is completely abandoned.
Here are two solutions:
I. added the timeout time limit.
Note: set_time_limit only sets the timeout time for your PHP program, rather than the timeout time for the file_get_contents function to read the URL.
At first, I thought that set_time_limit could also affect file_get_contents. later, it was tested to be invalid. You can use the timeout parameter of resource $ context to modify the file_get_contents latency:
The PHP code is as follows:
$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ));$context = stream_context_create($opts);$html =file_get_contents('http://www.bitsCN.com', false, $context);fpassthru($fp);
2. multiple attempts
The PHP code is as follows:
$cnt=0;while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){ $cnt++;}
The above method has timed out. Next we will demonstrate how to use file_get_contents to implement Post, as shown below:
PHP 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.bitsCN.com', $data);
Note that the Set_time_out in the document header is invalid. Otherwise, the entire document has timed out.
I hope this article will help you learn php programming.