Wednesday 13 June 2012

PHP/CURL Tutorial Part-1

Part-1
Getting Started with PHP/CURL

This Tutorial assume that you have already install Web Server and running PHP and cURL support.

Let's Start with cURL...

cURL is a library which allows you to connect and communicate to many different types of servers with many different types of protocols. cURL means “Client for URL’s” or “Client URL Request Library”. cURL project produce two products libcurl and curl.

libcurl is free and easy to use client side URL transfer library, thread-safe, IPv6 compatible.
curl is command line tool for getting or sending files using URL syntax.

What is PHP/CURL?
The module for PHP that makes it possible for PHP programs to access curl function from within PHP. PHP/CURL is written by Sterling Hughes.

Using PHP/CURL you can:

  • Write Script to fetch complete web page.
  • Implement payment gateways’ payment notification scripts.
  • Download and upload files from remote servers.
  • Login to other websites and access members only sections.
  • Log on to a website and automate tasks


Lets check if CURL installed...

write a small PHP code and run it.

//Check for curl installation
<?php
phpinfo();
?>
if curl support is enabled in PHP, the phpinfo() function will display it is in its output as below.
If not then install libcurl first.




Or simply you can put a small code in PHP script to check whether Curl functions are available or not

<?php
 if (!function_exists('curl_init')){
 die('Sorry cURL is not installed!');
 }
?>

PHP/CURL Tutorial Part-2


Learning PHP with libcurl...


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_initInitializes the session and returns a cURL handle which can be passed to other cURL functions.
  • curl_optThis is the main workhorse of cURL library. This function is called multiple times and specifies what we want the cURL library to do.
  • curl_execExecutes a cURL session.
  • curl_closeCloses the current cURL session.
let's have a small example and understand it better...
<?php
// Example for Simple Get Webpage
$url = "http://www.google.co.in";  // URL to get webpage contents.
$ch = curl_init();  // Initialize a CURL session.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return Page contents.
curl_setopt($ch, CURLOPT_URL, $url); // Pass URL as parameter.
$result = curl_exec($ch); // grab URL and pass it to the variable.
curl_close($ch); // close curl resource, and free up system resources.
echo $result; // Print page contents.
?>

The simple example above simply gets the contents of www.google.co.in and saves it in the variable $result.

Here’s a brief explanation...


$ch = curl_init ();
| Initialize  new curl session and return curl handle.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
| Tell php curl that we want the data returned to us instead of being displayed
curl_setopt ($ch, CURLOPT_URL, $url);
| Tell php curl that this is the url you want to get from internet.
$result = curl_exec ($ch);
| Execute curl and put the output in $result.
$curl_close ($ch);
| close curl resource  and  free system resource





Here is detailed explanation..

$ch = curl_init();
curl_init() — Initialize a cURL session.This is going to initialize the CURL library in your PHP script and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions.You can see we initialize the library and set it to what's called a "handle".  This is where this specific instance is initialized to be stored so that we can work with it. (here $ch is a handle for curl operation). curl_init() function Returns a cURL handle on success, FALSE on errors.
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.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
The curl_setopt() function is the way we make our settings in our CURL object. In this case we're setting an option in the handle we created/initialized using curl_init() function, $ch.The option we're setting is CURLOPT_RETURNTRANSFER, what this tells the curl object/handle is to return the transfer to a variable, in this case $result  variable, and not the screen. We want curl function to return webpage content to a variable so that we can do something with output like store it in database or file, regex to parse the data or whatever we want. If we didn't put this option then whole content will be displayed on screen and nothing will be stored in variable. The final parameter pass as TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. If we were to just put false here it'd be the same as not having it at all.

curl_setopt ($ch, CURLOPT_URL, $url);
Use it to specify the URL which you want to process. This could be the URL of the file you want to download or it could be the URL of the script to which you want to post some data.This option set value to The URL to fetch. This can also be set when initializing a session with curl_init().


$result = curl_exec($ch);
The one line meaning for this function is "run all the stuff we've set" in the lines preceding this and return the data scraped to the variable $result. Hope you will argu like we can do whole this stuff using this one line code. $result = file_get_contents("http://www.google.co.in"); Yes you’re absolutely right. In this example it doesn't make a lot of sense but this is going to allow us to do some things more that we can't do with just file_get_contents() function.

$curl_close ($ch);
Closes a cURL session and frees all resources. The cURL handle, $ch, is also deleted. and it will be no more available in program.
To know more feature of curl just read the next tutorial.

Thursday 26 April 2012

Install setup PHP Curl in linux and windows

To install or setup cURL on your Linux machine like Ubuntu,Mint, run the following line of shell command in your terminal:

sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

Now you have PHP cURL installed, the next thing you need to do is to restart apache2, run the following command in your terminal:

sudo /etc/init.d/apache2 restart

To install or setup cURL on windows

As with any PHP extension in Windows, you will need the PHP distribution that includes external extensions. Once PHP is installed, you will need to copy the files php4ts.dll, ssleay32.dll, php_curl.dll, msvcrt.dll from the ‘DLLs’ folder to your Windows PATH, i.e.:

c:\windows\system for Windows 9x/Me
c:\winnt\system32 for
Windows NT/2000
c:\windows\system32 for Windows XP

cURL can then be enabled by uncommenting the line ‘extension=php_curl.dll’ in the php.ini file.

Monday 27 February 2012

PHP Code for Sending free SMS through your way2sms account... :)

Guys here is code written in php for sending sms through your way2sms account. (UPDATED 13/06/2012)

This Code works fine for your small application where you want to send message through your website. Only thing you needed is an account on WAY2SMS . First create an account, then insert this code in your website and pass 4 argument to the function and just sit back and relax :), this code will do automatically everything for you..enjoy :)

You can download complete source in ZIP :
http://andromeda.nitc.ac.in/~ritesh/SmsApi/SmsApi.zip

Some Points to Remember...

  1. Some lines are truncated in this webpage so keep track of  double quote("") and new lines.
  2. You have to create a normal text file with the name cookie.txt and place it your local host or any folder and set absolute location of cookie file to $cookie_file_path_location variable. like this  $cookie_file_path_location ="/var/www/sms/cookie.txt";
    find Absolute path using php function realpath("your_cookie_fine_name");
  3. Cookie file must have full READ and WRITE permission. Give 777 permission in Linux and full read write permission in windows.
  4. Message length must be less than or equal to 140 character.
  5. By repeating Code for sending SMS in loop, you can send same message for many time without login and logout.
  6. Do not include '0' or '+91' before mobile number.
  7. Before using this code make sure you have installed PHP CURL libraries libcurl. It is necessary for executing this script. 


//Setting up variables 
$userID="9876543210"; //10 digit, way2sms id, from which admin will send SMS
$userPWD="123456"; // password for user id
$recerverNO="9876543210"; // recever's Number, who is going to receive sms
$message="Anything that you want to send but less than140 character"



******************** CODE START HERE ********************


function send_sms($userID,$userPWD,$recerverNO,$message)
{
     if(strlen($message)>140) // check for message length
         {echo "Error : Message length exceeds 140 characters" ; exit(); }
     if (!function_exists('curl_init')) // check for curl library installation
         {echo "Error : Curl library not installed";  exit(); }

     $message_urlencode=rawurlencode($message);
      // message converted into URL encoded form
     $cookie_file_path ="/var/www/oose/cookie.txt";
     // Cookie file location in your machine with full read and write permission

//START OF Code for getting sessionid
        $url="http://site5.way2sms.com/content/index.html";
        $header_array[0] = "GET /content/index.html HTTP/1.1";
        $header_array[1]= "Host: site5.way2sms.com";
        $header_array[2]= "User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1";
        $header_array[3]= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        $header_array[4]= "Accept-Language: en-us,en;q=0.5";
        $header_array[5]= "Accept-Encoding: gzip,deflate";
        $header_array[6]= "DNT: 1";
        $header_array[7] = "Connection: keep-alive";
        $ch = curl_init();   //initialise the curl variable
        curl_setopt($ch, CURLOPT_URL,$url);
        //set curl URL for crawling
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array); 
        //set the header for http request to URL 
        curl_setopt($ch, CURLOPT_REFERER, $reffer);  
         //set reffer url means it shows from where the request is originated.
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
         //it means after crawling data will return
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
        // store the return cookie data in cookie file 
        $result = curl_exec ($ch); // Execute the curl function 
        curl_close ($ch);
//END OF Code for getting sessionid

//START OF Code for automatic login and storing cookies
        $post_data = "username=".$userID."&password=".$userPWD."&button=Login";
        $url = "http://site5.way2sms.com/Login1.action";
        $header_array[0]="POST /Login1.action HTTP/1.1";
        $header_array[1]="Host: site5.way2sms.com";
        $header_array[2]="User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1";
        $header_array[3]="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        $header_array[4]="Accept-Language: en-us,en;q=0.5";
        $header_array[5]="Accept-Encoding: gzip, deflate";
        $header_array[6]="DNT: 1";
        $header_array[7]="Connection: keep-alive";
        $header_array[8]="Content-Type: application/x-www-form-urlencoded";
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
        curl_setopt($ch,CURLOPT_REFERER,"http://site5.way2sms.com/content/index.html");
        $content = curl_exec( $ch );
        $response = curl_getinfo( $ch );
        curl_close ($ch);
//END OF Code for automatic login  and storing cookies

// START OF Code is  getting way2sms unique user ID
        $url = "http://site5.way2sms.com/jsp/InstantSMS.jsp";
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        $content = curl_exec($ch);
        curl_close ($ch);
        $regex = '/input type="hidden" name="Action" id="Action" value="(.*)"/';
        preg_match($regex,$content,$match);
        $userID = $match[1];
// END OF Code for getting way2sms unique user ID

// START OF Code for sending SMS to Recever
        $post_data = "HiddenAction=instantsms&catnamedis=Birthday&Action=".$userID."&chkall=on&MobNo=".$recerverNO."&textArea=".$message_urlencode;
        $url = "http://site5.way2sms.com/quicksms.action";
        $header_array[0]="POST /quicksms.action HTTP/1.1";
        $header_array[1]="Host: site5.way2sms.com";
        $header_array[2]="User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1";
        $header_array[3]="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        $header_array[4]="Accept-Language: en-us,en;q=0.5";
        $header_array[5]="Accept-Encoding: gzip, deflate";
        $header_array[6]="DNT: 1";
        $header_array[7]="Connection: keep-alive";
        $header_array[8]="Content-Type: application/x-www-form-urlencoded";
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
   curl_setopt($ch,CURLOPT_REFERER,"Referer: http://site5.way2sms.com/jsp/InstantSMS.jsp");
        $content = curl_exec( $ch );
        $response = curl_getinfo( $ch );
        curl_close ($ch);
// END OF Code for sending SMS to Recever

//START OF Code for automatic logout
        $url = "http://site5.way2sms.com/jsp/logout.jsp";
        $header_array[0]="GET /jsp/logout.jsp HTTP/1.1";
        $header_array[1]="Host: site5.way2sms.com";
        $header_array[2]="User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1";
        $header_array[3]="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        $header_array[4]="Accept-Language: en-us,en;q=0.5";
        $header_array[5]="Accept-Encoding: gzip, deflate";
        $header_array[6]="DNT: 1";
        $header_array[7]="Connection: keep-alive";
        $cookie_file_path ="/var/www/oose/cookie.txt";
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
        curl_setopt($ch,CURLOPT_REFERER,"Referer: http://site5.way2sms.com/jsp/InstantSMS.jsp");
        $content = curl_exec( $ch );
        $response = curl_getinfo( $ch );
        curl_close ($ch);
//END OF Code for automatic logout

}// end function send_sms



******************** CODE END HERE ********************