Analysis on efficiency and stability of file_get_contents and curl

Source: Internet
Author: User
This article provides a detailed analysis of file_get_contents and curl efficiency and stability. For more information about the efficiency and stability of file_get_contents, I have done a lot of products to capture the content of other websites, however, there will always be a problem of retrieval failure. although timeout is set according to the example in the manual, it will not work in most cases:
The code is as follows:
$ Config ['context'] = stream_context_create (array ('http' => array ('method' => "GET ",
'Timeout' => 5 // the timeout is unstable and often does not work.
)
));

At this time, check the server connection pool and you will find a bunch of similar errors, causing you a headache:
File_get_contents (http: // ***): failed to open stream...
As a last resort, the curl Library is installed and a function replacement is written:
The code is as follows:
Function curl_file_get_contents ($ durl ){
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ durl );
Curl_setopt ($ ch, CURLOPT_TIMEOUT, 5 );
Curl_setopt ($ ch, CURLOPT_USERAGENT, _ USERAGENT _);
Curl_setopt ($ ch, CURLOPT_REFERER, _ REFERER _);
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
$ R = curl_exec ($ ch );
Curl_close ($ ch );
Return $ r;
}

In this way, there are no more problems except the real network problems.
This is a test on curl and file_get_contents that someone else has done:
File_get_contents:
2.31319094
2.30374217
2.21512604
3.30553889
2.30124092
Curl Time:
0.68719101
0.64675593
0.64326
0.81983113
0.63956594
Is there a big gap? In my experience, the two tools differ not only in speed, but also in stability. It is recommended that you use the above curl_file_get_contents function to capture network data with high stability requirements. this function not only ensures high stability, but also can spoof the target address with a fake browser!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.