Working with cURL in php

cURL is a very powerful library of PHP, also known as client URL (cURL).

It allows us to connect and communicate to many different types of servers. It is one of the best things I have worked with in php.

To work with cURL library your server must be compiled with this package.

A simple curl request

  function get_curl($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    $output = curl_exec($ch);
    return $output;

  echo get_curl("");

Working steps of the code :

1. First of all, you must initiate a session with the curl_init() function.
2. Next the cURL session is configured with the curl_setopt() function.
3. Execute the cURL session with curl_exec() function.
4. In the end close the cURL session with curl_close() function.

Use the curl_setopt() function to set options for the session according to your need. i.e. set the header, follow redirects, set timeout etc...

A curl request with multiple options set

  function get_curl($url){
  $agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: 
Gecko/20080311 Firefox/";

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $output = curl_exec($ch);
    return $output;

  echo get_curl("");

Description of curl_setopt options used above

Sets the url for the transfer

If set to true the output is returned as a string and if set to false the output is displayed directly on the browser.

If set to true, It follows the redirection of the url

The maximum amount of http redirection to follow. Used alongwith CURLOPT_FOLLOWLOCATION

It sets the user agent name.

If set to true it returns the http headers.

The maximum number of seconds to allow cURL functions to execute

Above function is good enough for a simple request. But this is not the end of the world. cURL can do amazing things. It is used to create webbots, spiders.

If you are working with https url set following two options.
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);

It also can be used to submit a form with its CURLOPT_POST and CURLOPT_POSTFIELDS option. Eg:

   $data = array('name' => 'your name', 'email' =>'');
   curl_setopt($ch, CURLOPT_POST, TRUE);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Have a look on Submit a form with curl.
You can get more curl_setopt option here.
Working with cURL in php Working with cURL in php Reviewed by Altaf Hussain on 10:21 PM Rating: 5

No comments:

Altaf Web. Powered by Blogger.