Curl_get_contents is more stable than file_get_contents sharing_PHP tutorial

WBOY
Release: 2016-07-21 15:22:13
Original
992 people have browsed it

Share an actually used function:

Copy 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. */
function curl_get_contents($url,$timeout=1) {
$curlHandle = curl_init();
curl_setopt( $curlHandle , CURLOPT_URL, $url );
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 It causes a long wait for the page, and can 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 comes from Zhang Yan. For details, 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 get the page is more stable than using file_get_contents.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324745.htmlTechArticleShare an actually used function: Copy the code as follows: /*Much more stable than file_get_contents! $timeout is the timeout time, the unit is seconds, and the default is 1s. */ function curl_get_cont...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!