cURL vs file_get_contents

// February 10th, 2010 // Blog Posts

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.

Using curl can be quite complicated, especially since it requires many lines of code. Here’s a function to simplify the process.

<?php
function curl_get_contents($url) {
	// Initiate the curl session
	$ch = curl_init();
	// Set the URL
	curl_setopt($ch, CURLOPT_URL, $url);
	// 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
	$output = curl_exec($ch);
	// Close the curl session
	curl_close($ch);
	// Return the output as a variable
	return $output;
}
?>

This function is just like file_get_contents. To use it, use the following piece of code:

<?php
$output = curl_get_contents('http://www.example.com/');
echo $output;
?>

One Response to “cURL vs file_get_contents”

  1. kar says:

    using curl we can post, put and also get. but file_get_contents is only get.

Leave a Reply