cURL is a library which allows you to connect and communicate to many different types of servers with many different types of protocols. Using cURL you can:

  • Implement payment gateways’ payment notification scripts.
  • Download and upload files  from remote servers.
  • Login to other websites and access members only sections.

PHP cURL library is definitely the odd man out. Unlike other PHP libraries where a whole plethora of functions is made available, PHP cURL wraps up a major parts of its functionality in just four functions.

A typical PHP cURL usage follows the following sequence of steps.

curl_init – Initializes the session and returns a cURL handle which can be passed to other cURL functions.

curl_opt – This is the main work horse of cURL library. This function is called multiple times and specifies what we want the cURL library to do.

curl_exec – Executes a cURL session.

curl_close – Closes the current cURL session.

Below are some examples which should make the working of cURL more clearer.

The below piece of PHP code uses cURL to download Google’s RSS feed.

  1. <?php
  2. /**
  3. * Initialize the cURL session
  4. */
  5. $ch = curl_init();
  6. /**
  7. * Set the URL of the page or file to download.
  8. */
  9. curl_setopt($ch, CURLOPT_URL,
  10. ‘http://news.google.com/news?hl=en&topic=t&output=rss’);
  11. /**
  12. * Ask cURL to return the contents in a variable
  13. * instead of simply echoing them to the browser.
  14. */
  15. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  16. /**
  17. * Execute the cURL session
  18. */
  19. $contents = curl_exec ($ch);
  20. /**
  21. * Close cURL session
  22. */
  23. curl_close ($ch);
  24. ?>

As you can see, curl_setopt is the pivot around which the main cURL functionality revolves. cURL functioning is controlled by way of passing predefined options and values to this function.

The above code uses two such options.

  • CURLOPT_URL: Use it  to specify the URL which you want to process. This could be the URL of the file you want to download or it could be the URL of the script to which you want to post some data.
  • CURLOPT_RETURNTRANSFER: Setting this option to 1 will cause the curl_exec function to return the contents instead of echoing them to the browser.
eXTReMe Tracker