Regarding the advanced usage of file_get_contents, first solve the timeout problem of file_get_contents. After the timeout returns an error, make a try like settimeout in js. After more than 3 or 5 errors, it is confirmed that the server cannot be connected. completely give up.
Here are two simple solutions:
1. Increase the time limit of timeout
Note: set_time_limit is just Set the timeout for your PHP program, not the timeout for the file_get_contents function to read the URL.
I initially thought that set_time_limit could also affect file_get_contents, but it was later tested to be invalid. To truly modify the file_get_contents delay, you can use the timeout parameter of 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('//m.sbmmt.com', false, $context); fpassthru($fp);
2. Multiple attempts
The PHP program code is as follows:
$cnt=0; while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){ $cnt++; }
The above method is OK to deal with timeout. Next, we will demonstrate 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('//m.sbmmt.com', $data);
Pay attention to the Set_time_out in the document header, otherwise the entire document will time out.
Related recommendations:
The difference between php fopen() and file_get_contents() is explained in detail
cURL is better than file_get_contents() in php Detailed explanation of examples
10 recommended articles about file_get_contents
The above is the detailed content of Advanced usage sharing of file_get_contents. For more information, please follow other related articles on the PHP Chinese website!