Home >Backend Development >PHP Tutorial >Curl_get_contents sharing is more stable than file_get_contents

Curl_get_contents sharing is more stable than file_get_contents

WBOY
WBOYOriginal
2016-07-29 08:47:42952browse

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.

Another optimization of file_get_contnets from Zhang Yan, please see: http://www.jb51.net/article/28030.htm
The timeout is also set to solve this problem. If curl is not installed, you must use this method.



Copy code

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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn