cURL vs file_get_contents

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 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.

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
	// 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:

$output = curl_get_contents('');
echo $output;

3 thoughts on “cURL vs file_get_contents

    1. Tech163 Post author

      For me, no significant difference CPU wise. Time wise, much faster. Even if file_get_contents use less memory/CPU (which it doesn’t, though it might depending on your server), it will be holding onto it for longer as long as it’s slower.

Leave a Reply

Your email address will not be published.