Saturday, 5 October 2013

file_get_contents vs cURL


In this Post,I will explain difference between file_get_contents and curl.

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.knowledgecornor.com/ took 0.198035001234 seconds. Meanwhile, using curl to retrieve the same file took 0.025691986084 seconds. As you can see, curl is much faster.

file_get_contents - It is a function to get the contents of a file(simply view source items i.e out put html file contents).

curl - It is a library to do more operations, for example get the contents like file_get_contents, sending and receiving data from one site to another site and it also supports different types of protocols like http, https, ftp, gopher, telnet, dict, file, and ldap. curl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading HTTP form based upload, proxies, cookies.

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.knowledgecornor.com/');
echo $output;
?>

No comments:

Post a comment