Quick PHP cURL Tutorial

(External source and originally from the Internet as most php tutorials. )

 

Introduction

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:

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.

 

Examples

Example 1 - Fetch Yahoo Home Page

<?php

$ch = curl_init("http://www.yahoo.com/");
$fp = fopen("myyahoo_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

 

Example 2 - Download RSS Feed

/**
* Initialize the cURL session
*/
$ch = curl_init();

/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL, ‘http://news.google.com/news?hl=en&topic=t& output=rss’);

/**
* Ask cURL to return the contents in a variable instead of simply echoing them to the browser.
*/
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

/**
* Execute the cURL session
*/
$contents = curl_exec ($ch);

/**
* Close cURL session
*/
curl_close ($ch);

Example 2 Notes:

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.

 

Example 3 - Download web page and save to file - Long

/**
* Initialize the cURL session
*/
$ch = curl_init();

/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL, ‘http://news.google.com/news?hl=en&topic=t& output=rss’);

/**
* Create a new file
*/
$fp = fopen(‘rss.xml’, ‘w’);

/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);

/**
* Execute the cURL session
*/
curl_exec ($ch);

/**
* Close cURL session and file
*/
curl_close ($ch);
fclose($fp);

Example 3 Notes:

Here we have used another of the cURL options, CURLOPT_FILE. Obtain a file handler by creating a new file or opening an existing one and then pass this file handler to the curl_set_opt function.

cURL will now write the contents to a file as it downloads a web page or file.