Working with CURL libraries in PHP

cURL is command line protocol for transferring data using different protocols. PHP library that provides usage of cURL data transfer is called libcurl and can be easily implemented. For most linux systems, installation of curl with PHP can be done with following command as root:

apt-get install php5-curl

For Debian like systems, restart Apache with command:

/etc/init.d/apache2 restart

And you are ready for using cURL extension. Complete guide and documentation for using and setting up curl on different systems can be found at http://curl.haxx.se

cURL supports many protocols: http, https, ftp, gopher, telnet, dict, file, etc. A lot of things can be done with cURL, so it’s not surprise that it is the most popular PHP extension.

It’s easy to start with cURL as it has only few functions that are required for successful executing:

curl_init() – function for initializing curl session

curl_setopt() – defining different parameters for current curl session

curl_exec() – function for executing

curl_close() – closing curl programme

One simple curl script for downloading web site would look like this:


$td = curl_init();

$file = fopen('webpage.html','w'); 

curl_setopt($td, CURLOPT_URL, 'http://firescripts.net'); 
curl_setopt($td, CURLOPT_HEADER, 0); 
curl_setopt($td, CURLOPT_FILE, $file); 

curl_exec($td);

curl_close($td);

fclose($file);

We start the script with curl_init() function and open file ‘webpage.html’ for writing where the whole website content is going to be stored.

curl_setopt() is function where the majority important of things are specified. Parameters that I set with this function are:

CURLOPT_URL – (string value) url for the data we want to store
CURLOPT_HEADER – (boolean value) 1 for including header in the output , 0 to ignore it
CURLOPT_FILE – (file handle) the file that the transfer should be written toFor complete list of options, see http://php.net/manual/en/function.curl-setopt.php

curl_exec() and curl_close() are functions for executing code and closing the curl session respectively

Leave a Reply

Your email address will not be published. Required fields are marked *