Home > Article > Backend Development > Advanced usage of file_get_contents, file_get_contents_PHP tutorial
First solve the timeout problem of file_get_contents. After the timeout returns an error, try again like settimeout in js. If the error exceeds 3 or 5 times After that, it was confirmed that it could not connect to the server and gave up completely.
Here are two simple solutions:
1. Increase the timeout time limit
Note: set_time_limit only sets the timeout time of your PHP program, not the file_get_contents function read The timeout period for retrieving 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:
PHP code
$opts = array(
'http'=>array(
'method'= > ;"GET",
'timeout'=>60,
)
file_get_contents ('http://www.example.com', false, $context);
fpassthru($fp);
2. Multiple attempts
PHP code
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){
$cnt++;
}
The above method is OK for dealing with timeouts. Next, let’s demonstrate using file_get_contents to implement Post, as follows:
PHP code
function Post($url, $post = null){
$context = array();
if ( is_array($post)) {
method' = > 'POST',
'content' => http_build_query($post, '', '&'),
, stream_context_create($context));
}
$data = array (
'name' => 'test',
'email' => 'test@gmail. com',
'submit' => 'submit',
);
echo Post('http://www.example.com', $data);
Pay attention to the Set_time_out in the file header, otherwise the entire file will time out
Usage of file_get_contents
file_get_contents — Read the entire file into a string
How to use php’s file_get_contents
file_get_contents() reads the contents of a file, including remote files!!
file_get_contents() function is the preferred method for reading the contents of a file into a string!!
< ?php
echo file_get_contents('www.baidu.com');
?>