Loading ...
Sorry, an error occurred while loading the content.

CURL : Client URL Library

Expand Messages
  • Rupom
    Hi All, Find a nice article on CURL. You can download this article as doc from the group site. CURL: Client URL Library ... Introduction: When it is time for
    Message 1 of 1 , Jan 28, 2006
    • 0 Attachment
      Hi All,
      Find a nice article on CURL. You can download this article as doc from the group site. 
      CURL: Client URL Library
      ----------------------------------------------------------------------------------
      Introduction:
      When it is time for you to start dealing with Merchant accounts, CURL is your answer to saving you a lot of money on API's and PHP Wrappers to those API's.
      CURL is introduced in the PHP manual as: "PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication."
      Most merchant servers work based upon a gateway where you send your information that the user posts from a form to be check against the processing server. Using CURL, you can make these transactions completely invisible and even use your same merchant account on as many servers as you would like.
      Every time a client requests that I build a payment processing script for them, I use CURL. What does CURL do? CURL basically sends the information to the destination and allows you to retrieve a result all within the same process of the script that you are using. If you are smart enough, and swift enough, you can conquer any merchant account system with using CURL and PHP. What's even better, is you can setup your own methods of handling the result codes.
      Let's take a look at a basic Merchant Account setup that I've used personally in the past. When I contacted this company to setup a merchant account, I got the merchant account and the payment gateway. I was also setup on a "Basic HTML" plan because it was quite a bit cheaper and I did not feel like paying outrageous prices for their API's and their API gateway. It was quite pointless doing such a thing when we have CURL and CURL is free :)
      Take a look at this diagram below. You'll see how my old merchant account wanted me to process a payment.
      .
      To sum up what is happening above, I had to specify ONE website URL that my payments could be processed from and I had to specify a "Thank You" page that the user would be redirected to if their payment was a success and a "Sorry" page that the user would be directed to if their payment failed. The final alternative would be just to let the user process their information on my merchant account's website and then I'd only be notified via Email if the payment was a success. What fun is that? I definately does not produce a professional image. Also, after a client ordered 5 items from my shopping cart, I would have to go in and manually process the order or grant access to a membership of the website. Who has time for all of that? Not me!
      Let's move on and see how CURL can make our life as a PHP Developer much easier.
       How CURL Works
      Now that we have seen the casual way of processing a payment, let's dive into some PHP fun and process payments how we want to do it.
      First, you'll need to ensure that you have CURL installed and PHP is compiled for it. You can grab the CURL installations for nearly any operating system at: http://curl.haxx.se/ (For FREE!) And compile PHP with it. Add this to your ./configure line: --with-curl=DIR (DIR is usually /usr).
      TIP: You can find out if PHP has curl support installed by running <? phpinfo(); ?> inside a script. Look for a section called CURL.
      After you are sure that CURL has been installed, let's look at how CURL works.
      Looking at the diagram below, you'll see that CURL can post the information to the processing server, open the page the user would normally see and parse it into a string using output buffering and then extract the information from the results. Don't worry, I'll show you how to do it all.
      Ok, we've got the picture of what CURL is supposed to do. Let's make it happen now! Look below at this PHP Script. Our first script we're going to develop for this tutorial is a mock up of what a processing server would do.
      This script is not required for you to use CURL. It's strictly a TEST server for us to explain what happens in this tutorial:
      Example:
       
      <?
      if(
      $_SERVER['HTTP_REFERER'] != "http://www.mysite.com/payment_form.html"){
          
      $response = "Server Response: Error - You are not allowed to access this payment gateway.<br />";
          
      $response .= $_SERVER['HTTP_REFERER']." is not granted access!\n";
          echo
      $response;
          exit();
      }

      if(!
      $_POST['firstname'] || !$_POST['lastname'] || !$_POST['ccnumber'] || !$_POST['expmonth'] || !$_POST['expyear']){
          echo
      "Server Response: Error - Missing or Invalid Information\n";
          exit();
      } else {
          if(
      $_POST['ccnumber'] != 4111111111111111){
              echo
      "Server Response: Error - Invalid Credit Card Number\n";
              exit();
          }
      }
      echo "Server Response: Transaction Success!\n";
      ?>
       
       
       
      I'm not going to break the script above down into little chunks of code and explain them to you. There's no need because as I said, it's not required to use CURL. All that is happening here is we are doing some error checking on the information posted to the script and in turn returning a response based on the information we've sent. I made this example because I want to show you the different responses. I'm sure you understand.
      Our PHP/CURL Script
      Let's move on to the actual script on our website that will send information to the previous script for testing.
      I'm going to start out with a simple HTML header:
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
      <html>
      <head>
      <title>PHP Curl Test</title>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      </head>
      <body>
      <center><h1>PHP Curl Test</h1></center>
      Now, let's start this script off using a SWITCH structure to navigate the script. I wanted to add this for you so we could teach you a little something extra during each tutorial. Using a switch allows you to combine multiple PHP scripts into one, using a "case" to seperate them. Check out this Function Based PHP Tutorial if you need any help figuring it out.
      I'll dump the code here and then break it down on the next page.
      PHP Example: (!)
      <?
      switch(
      $_REQUEST['cmd']){
          default:
              include
      'form.html';
          break;
          
          case
      "post":
              
      $postfields = array();
              
      $postfields[] = array("firstname", $_POST['firstname']);
              
      $postfields[] = array("lastname", $_POST['lastname']);
              
      $postfields[] = array("ccnumber", $_POST['ccnumber']);
              
      $postfields[] = array("expmonth", $_POST['expmonth']);
              
      $postfields[] = array("expyear", $_POST['expyear']);
              
              foreach(
      $postfields as $subarray) {
                   list(
      $foo, $bar) = $subarray;
                   
      $bar = urlencode($bar);
                   
      $postedfields[]  = "$foo=$bar";
              }
              
              
      $urlstring = join("\n", $postedfields);
              
      $urlstring = ereg_replace("\n", "&", $urlstring);
              
      // echo $urlstring;
              
              
      $ch = curl_init("http://mysite.com/curl/curlresponse.php");
              
      curl_setopt($ch, CURLOPT_HEADER, 0);
              
      curl_setopt($ch, CURLOPT_POST, 1);
              
      curl_setopt($ch, CURLOPT_POSTFIELDS, $urlstring);
              
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
              
      curl_setopt($ch, CURLOPT_REFERER, "http://www.mysite.com/payment_form.html");
              
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
              
      $data = curl_exec($ch);
              
      curl_close($ch);
              
              
      $response_start = strPos($data, "Server Response:");
              
      $response_end = strPos($data, "\n");
              
      $temp_code = substr($data, $response_start, ($response_end - $response_start));
              
      $temp_code = str_replace("Server Response:", "", $temp_code);
              
      $temp_code = strip_tags($temp_code);
              
      $transaction_code = trim($temp_code);
              
              switch(
      $transaction_code){
                  case
      "Transaction Success!":
                      
      //redirect person to thank you page
                      
      echo "Thank you for your purchase!";
                  break;
                  
                  default:
                      echo
      '<font color="red">Transaction Error: '.$transaction_code.'</font>';
                      include
      'form.html';
                  break;
              }
          break;
      }

      ?>
       
         
      CURL Code Breakdown
      The script I gave you on the last page kind of looks pretty mean. It uses arrays, foreach loops, output buffering and a few other things. Don't be intimidated if you haven't seen it before, I'll do my best to tell you what each section does as we plug along through it.
      First, we'll skip down to the first section of our switch. This is where I defined the default action of the switch if no the "$_REQUEST['cmd']" is empty, the switch will direct you automatically to the default section I have included the html form to gather credit card information. This form contains 5 fields: First Name (firstname), Last Name (lastname), Credit Card Number (ccnumber), Card Expiration Month (expmonth) and Card Expiration Year (expyear). Those fields are posted to the "post" case and now we'll look at this case.
      PHP Example: (!)
      case "post":
       
      The next item on our list of things to do is to create a special array of the post fields. This, in my opinion, is an easier way of creating the URL Query String of Post Fields that we need to tell CURL to use. I'm giving you this example for a reason, because it's a good exercise in building a multidemensional array and then extracting the information into a list inside a foreach loop.
      Let's build our array:
      PHP Example: (!)
      $postfields = array();
      $postfields[] = array("firstname", $_POST['firstname']);
      $postfields[] = array("lastname", $_POST['lastname']);
      $postfields[] = array("ccnumber", $_POST['ccnumber']);
      $postfields[] = array("expmonth", $_POST['expmonth']);
      $postfields[] = array("expyear", $_POST['expyear']);
       
      Now that our Array is built, let's extract array using a foreach loop and then build a query string out of the list.
      PHP Example: (!)
      foreach($postfields as $subarray) {
           list(
      $foo, $bar) = $subarray;
          
      $bar = urlencode($bar);
          
      $postedfields[]  = "$foo=$bar";
      }
       
      If you understand what I have just done, then good. If not, here's what I did. I created a new array called $postfields and it contains array elemenst of postfield=value.
      Now, let's join array and then prepare to use it in CURL.
      PHP Example: (!)
      $urlstring = join("\n", $postedfields);
      $urlstring = ereg_replace("\n", "&", $urlstring);
       
      We have now created a good long query string that contains all of our form posted elements and their values. It would look something like this:
      firstname=First+Name&lastname=Last+Name&ccnumber=4111111111111111&expmonth=10&expyear=2005
      That query string can be complicating to work with.
      Note: There are easier ways to build this query string, however, the ways that I am aware of do not limit you only to the items you want posted from the form. I would be very cautious using another method if you do not know what it does. This one works, so I'm going to teach you this method.
      So, we have our query string built and we are going to move on to starting CURL. I'm going to do my best to break down each element of the CURL functions that we are going to use and explain them. Here we go.
      PHP Example: (!)
      $ch = curl_init("http://mysite.com/curl/curlresponse.php");
       
      The above code defines $ch as the curl_init function and allows us to build our curl response. The URL that you see inside the curl_init() is where CURL is going to submit this information to. Notice the URL is bogus in this example, so you'll have to modifiy it with your website. This is pointing to our test curlresponse.php script that I gave you earlier in this tutorial.
      PHP Example: (!)
      curl_setopt($ch, CURLOPT_HEADER, 0);
       
      Using the curl_setopt function, or "Curl Set Options", we start defining what options we are going to use when we execute the curl code. Here, I have defined CURLOPT_HEADER to 0. This option means that I do not want the HEADER to be displayed in the output of this code. All of the curl_setopt options can be found on the curl_setopt function page.

      (Message over 64 KB, truncated)
    Your message has been successfully submitted and would be delivered to recipients shortly.