Home >Backend Development >PHP Tutorial >Curl_get_contents sharing is more stable than file_get_contents
Share an actually used function:
Copy the code The code is as follows:
/*Much more stable than file_get_contents! $timeout is the timeout time, the unit is seconds, and the default is 1s. */ UFunction Crl_get_Contents ($ Url, $ Timeout = 1) {
$ Curlhandle = Curl_init (); Curl_Setopt ($ Curlhandle, Curlopt_returntransfer, 1);
CURL_SETOPT ($ curlHandle , CURLOPT_TIMEOUT, $timeout );
$result = curl_exec( $curlHandle );
curl_close( $curlHandle );
return $result;
}
$hx = curl_get_contents('http://www.jb51.net') ;
I believe that friends who have used the file_get_contents function know that when the obtained $url cannot be accessed, it will cause the page to wait for a long time, and even cause the PHP process to occupy 100% of the CPU, so this function was born. Some common sense introduction to curl
The reason for retaining the original file_get_contents function is that when reading local files, it is obviously more appropriate to use the native file_get_contents.
The code is as follows:$ctx = stream_context_create(array(
'http' => array('timeout' => 1 //Set a timeout in seconds
)
)
);
file_get_contents("http://www.jb51.net/", 0, $ctx);
In addition, according to incomplete testing, using curl to obtain pages is more stable than using file_get_contents.
The above has introduced the sharing of curl_get_contents, which is more stable than file_get_contents, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.