Saturday, 25 October 2014

file_get_contents VS CURL, what has better performance?

PHP offers two main options to get a remote file, curl and file_get_contents. There are many difference between the two. Curl is a much faster alternative to file_get_contents.
Using file_get_contents to retrieve http://www.example.com/ took 0.198035001755 seconds. Meanwhile, using curl to retrieve the same file took 0.025691986084 seconds. As you can see, curl is much faster.

After googling I came to the conclusion even though curl is lot complex but it lik atleast 30% times faster than the former one.

I just did some quick benchmarking on this.
Fetching google.com using file_get_contents took (in seconds):
2.31319094
2.30374217
2.21512604
3.30553889
2.30124092
CURL took:
0.68719101
0.64675593
0.64326
0.81983113
0.63956594

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.

file_get_contents requires allow_url_fopen to be TRUE.
allow_url_fopen = 1
 

Syntax to use file_get_contents()

$result = file_get_contents('https://www.google.co.in');

Syntax to use curl()

// Initiate the curl session
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, 'https://www.google.co.in');
// Removes the headers from the output
curl_setopt($ch, CURLOPT_HEADER, 0);
// Return the output instead of displaying it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the curl session
$result = curl_exec($ch);
// Close the curl session
curl_close($ch);
// Return the output as a variable
return $output;
 


No comments:

How calulation total value for HTML input text?

<script> $j(document).ready(function(){ $j(":text").keyup(function(){ if (isNaN($j(this).val())) { alert(...