Friday, March 30, 2007

PHP-CURL and You

The first step in using CURL is to create a new CURL resource, by calling the curl_init() function, like so:
// create a new curl resource
$ch = curl_init();
?>

Now that you've got a curl resource, it's possible to retrieve a URL, by first setting the URL you want to retrieve using the curl_setopt() function:
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/");
?>

After that, to get the page, call the curl_exec() which will execute the retrieval, and automatically print the page:
// grab URL and pass it to the browser
curl_exec($ch);
?>

Finally, it's probably wise to close the curl resource to free up system resources. This can be done with the curl_close() function, as follows:
// close curl resource, and free up system resources
curl_close($ch);
?>

That's all there is to it, and the above code snippets together form the following working demo:

// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.google.nl/");

// grab URL and pass it to the browser
curl_exec($ch);

// close curl resource, and free up system resources
curl_close($ch);

?>


The only problem we have now is that the output of the page is immediately printed, but what if we want to use the output in some other way? That's no problem, as there's an option called CURLOPT_RETURNTRANSFER which, when set to TRUE, will make sure the output of the page is returned instead of printed. See the example below:

// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.google.nl/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// grab URL, and return output
$output = curl_exec($ch);

// close curl resource, and free up system resources
curl_close($ch);

// Replace 'Google' with 'PHPit'
$output = str_replace('Google', 'PHPit', $output);

// Print output
echo $output;

?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

No comments: