What is cURL

cURL stand for Client URL. cURL is a library to transfer data via various protocol like http, ftp, tftp etc. By using cURL we can send HTTP request using various method like GET, POST etc. First cURL library was released in 1997. cURL project was originally started by Daniel Stenberg. cURL project has 2 part, cURL command line tool and libcurl library. Command line tool is generally available in linux distributions for transferring data on various protocol like HTTP, HTTPS, FTP etc. Libcurl is library which support data transfer on different protocol.

All cURL feature in PHP is available through libcurl. In the series of PHP cURL we will explore around the various aspect of libcurl in php.

Below are some general thing which we can do using php curl library

  1. Downloading HTML from URL in our PHP Code.
  2. Sending POST request on any URL. 
  3. Calling Rest full API.

cURL support in php is introduced from php version 4.0.2

Basic code:

 

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, “http://www.google.co.in&#8221;);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
print $result;
?>

 

Above code is fetching homepage of url http://www.google.co.in .  Below thing we are doing in above code.

  1. Initializing curl.
  2. Setting option URL to google.com.
  3.  Setting option to transfer data as string.
  4. Executing Curl and taking output string in a variable.
  5. Closing the curl handle.
  6. printing result.

In above code we have used some methods like curl_init , curl_setopt, curl_close which are function available with curl library of php.

 

cURL Function

PHP cUrl library provides 29 function. You can get full list of php curl function here. Let us look at some of imporent cURL function:

  1. curl_init
  2. curl_setopt & curl_setopt_array
  3. curl_exec
  4. curl_getinfo
  5. curl_close
  6. curl_error
  7. curl_errorno

Most of the time we cant debug cURL, but have very important function for help curl_error() &  Curl_errorno()

curl_error : Function return last error of the curl_session. If error will not occur then it will return empty string.

<?php
$curl = curl_init(‘http://404.techflirt.com’);
$result = curl_exec($curl);
if(false == $result){
echo curl_error($curl);
}
curl_close($curl);
?>

Curl_errorno : Function return last error number of curl_session.

I would like to thanks techflirt for all detail information on: http://www.techflirt.com/php/php-curl/index.html

Advertisements