Tuesday 22 April 2014

jQuery: Difference between parent(), parents() and closest()

HTML

<xmp>
<html lang="en">
  <head>
     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  </head>
  <body>
     <div>
        
            <a href="https://www.blogger.com/blogger.g?blogID=5288802523561781990#" id="anchorTag">Click here</a>
         


      </div>
</body>
</html>

jQuery
   $('#anchorTag').parent();      //This would return p, immediate parent of a#anchorTag.
parents(selector) : This returns the multiple ancestors. Its not restricted to only one level of parent/ancestors of the element. This is the main difference between the parent and parents method.
In the above HTML Snippet. If i do
   $('#anchorTag').parents();        //This would return all the ancestors (p, div, body, html)

   //On passing selector it will filter down the matched parent elements by selector

   $('#anchorTag').parents('div');   //This would give me only div
closest(selector) : It works like parents(), except that it returns only one parent/ancestor. This is ideal for the situation i mentioned earlier. If i want to check for existence of element in the ancestry tree, then i would prefer to use the closest rather than parents as it only target the selector rather than filtering it from all the ancestor elements. Here is example
$('#anchorTag').closest();           //This would give me empty object as we have not mentioned the selector
$('#anchorTag').closest('div');      //This would give me the div.
Hope this post has helped in terms of using the parent, parents and closest methods of jQuery library. Thank you for reading.

Monday 14 April 2014

Export database table data to excel format

Export database table data to excel format

Select the table to be exported to Excel Format
excel.php
<table style="width:100%;left:0px;position:relative;empty-cells:show;" border=0 cellpadding=0 cellspacing=0>
<tr height=50>
    <td style="color:#CC3300;font-size:13px;font-weight:bold;">Select the table to be exported to Excel Format</td>
   
</tr>
<tr>
    <td style="color:blue;font-size:12px;">Select Table</td>
</tr>
<tr>
    <td style="color:blue;font-size:12px;">
    <select name="selected_table" >
    <option value=""> </option>
    <?php 
            $fromdb=$_SESSION['COMPANY_DB'];
            $sql = "SHOW TABLES FROM ".$fromdb;
            $result = mysql_query($sql);
            while ($row = mysql_fetch_row($result))
            {
                        $table=$row[0];
                        echo "<option value=$table>$table</option>";
            }   
    ?>
    </select>
    </td>
</tr>
</table>
<BR></br>
<input type=submit name="export" value="Export">
export.php
if($export)
{
            $my_table=$_REQUEST['selected_table'];
            $result = mysql_query('select * from '.$my_table);
            $count = mysql_num_fields($result);
           
            for ($i = 0; $i < $count; $i++){
            $header .= mysql_field_name($result, $i)."\t";
            }
           
            while($row = mysql_fetch_row($result)){
            $line = '';
            foreach($row as $value){
            if(!isset($value) || $value == ""){
            $value = "\t";
            }else{
            # important to escape any quotes to preserve them in the data.
            $value = str_replace('"', '""', $value);
            # needed to encapsulate data in quotes because some data might be multi line.
            # the good news is that numbers remain numbers in Excel even though quoted.
            $value = '"' . $value . '"' . "\t";
            }
             
           
            $line .= $value;
            }
            $data .= trim($line)."\n";
            }
            # this line is needed because returns embedded in the data have "\r"
            # and this looks like a "box character" in Excel
            $data = str_replace("\r", "", $data);
           
             
            # Nice to let someone know that the search came up empty.
            # Otherwise only the column name headers will be output to Excel.
            if ($data == "") {
            $data = "\nno matching records found\n";
            }
           
            header("Content-type: application/x-msdownload");
            # This line will stream the file to the user rather than spray it across the screen
            //header("Content-Type: application/vnd.ms-excel; name='excel'");
           
           
           
            header("Content-Disposition: attachment; filename=excelfile.xls");
            header("Pragma: no-cache");
            header("Expires: 0");
           
            echo $header."\n".$data;
           
            //print "done";
}
header("Location: excel.php");

PHP Interview Questions

How to prevent web browser to image caching?       

The simple way to prevent image caching is to append time stamp with the name on image.
Ex- <img src=’image.jpg?<?php echo time() ?>’ />

What is the difference between Primary Key and Unique key?    

Both Primary Key and Unique Key enforces uniqueness of the column on which they are defined. But by default Primary Key creates a Clustered Index on the column, where are Unique Key creates a Non clustered Index by default. Another major difference is that, Primary Key doesn’t allow Nulls, but Unique Key allows one NULL only.

What is the difference between $name and $$name?

$name is variable where as $$name is reference variable
like $name=Sadiq and $$name=Akhtar so $Sadiq value is Akhtar.

What’s the difference between md5(), crc32() and sha1() crypto on PHP?        

The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit md5() returns a 160 bit value. This is important when avoiding collisions.

jQuery interview questions


How is body onload() function is different from document.ready() function used in jQuery?

1. We can have more than one document.ready() function in a page where we can have only one onload function.
2. Document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.
  • Is jQuery a library for client scripting or server scripting?
    Ans: Client scripting
  • Is jQuery a W3C standard?
    Ans: No
  • What are jQuery Selectors?
    Ans: Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS, Element name and hierarchical position of the element.
  • The jQuery html() method works for both HTML and XML documents?
    Ans: It only works for HTML.
  • Which sign does jQuery use as a shortcut for jQuery?
    Ans: $(dollar) sign.
  • What does $("div") will select?
    Ans: It will select all the div element in the page.
  • What does $("div.parent") will select?
    Ans: All the div element with parent class.
  • What is the name of jQuery method used for an asynchronous HTTP request?
    Ans: jQuery.ajax()
  • What is CDN and what are the advantage of loading jQuery framework from CDN?
  • How to load jQuery locally when CDN fails?
  • What is jQuery.noConflict()
  • Difference between $(this) and 'this' in jQuery
  • jQuery empty() vs remove()
  • jQuery remove() vs detach()
  • Is window.onload is different from document.ready()
  • How to check if element is empty
  • width() vs css('width') and height() vs css('height')
  • How to Check element exists or not in jQuery
  • Difference between bind() vs live() vs delegate() function
  • How to use jQuery Selectors with Examples
  • How to Disable-Enable all controls of page using jQuery
  • What are the possible problems can occur when jQuery and Ajax used in ASP.NET?
  • Why to use Google hosted jQuery CDN?
  • Q1. What is jQuery?
    Ans: jQuery is Lightweight and CrossBrowser JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. The biggest advantage over Javascript is that it reduces lines of code as huge code written in JavaScript, can be done easily acheived with jQuery in few lines.

    Q2. Why jQuery?
    Ans: Due to following functionality.
           1. Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
           2. AJAX functions
           3. CSS functions
           4. DOM manipulation
           5. DOM transversal
           6. Attribute manipulation
           7. Event detection and handling
           8. JavaScript animation
           9. Hundreds of plug-ins for pre-built user interfaces, advanced animations, form validation etc.
           10. Expandable functionality using custom plug-ins

    Q3. Is jQuery replacement of Java Script?
    Ans: No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML. 

    Q4. What is the basic need to start with jQuery?
    Ans: To start with jQuery, one need to make reference of it's library. The latest version of jQuery can be downloaded from jQuery.com.

    Q5. What does dollar Sign ($) means in JQuery?
    Ans: Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code. 
    $(document).ready(function(){
    });
    
    Over here $ sign can be replaced with "jQuery" keyword. 
    jQuery(document).ready(function(){
    });
    Q6. Is there any difference between body onload() function document.ready() function used in jQuery?
    Ans: document.ready() function is different from body onload() function due to 2 reasons.
           1. We can have more than one document.ready() function in a page where we can have only one body onload function.
           2. document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

    Q7. Can we have multiple document.ready() function on the same page?
    Ans: YES. We can have any number of document.ready() function on the same page.

    Q8. What are the different type of selectors in Jquery?
    Ans: There are 3 types of selectors in Jquery
           1. CSS Selector
           2. XPath Selector
           3. Custom Selector

    Q9. Name some of the methods of JQuery used to provide effects?
    Ans: Some of the common methods are :
           1. Show()
           2. Hide()
           3. Toggle()
           4. FadeIn()
           5. FadeOut()

    Q10. What is JQuery UI?
    Ans: jQuery UI is a library which is built on top of jQuery library. jQuery UI comes with cool widgets, effects and interaction mechanism. 

PHP-Mysql Interview Questions

PHP, Ajax, Javascript , HTML, Mysql

How can we submit a form without a submit button?

The main idea behind this is to use Java script submit() function in order to submit the form without explicitly clicking any submit button. You can attach the document.formname.submit() method to onclick, onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the form after xx seconds once the loading is done (can be seen in online test sites).

In how many ways we can retrieve the data in the result set of MySQL using PHP?

You can do it by 4 Ways
1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc
 
What is the difference between mysql_fetch_object and mysql_fetch_array?

mysql_fetch_object() is similar tomysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
 
What is the difference between $message and $$message?
 
It is a classic example of PHP’s variable variables. take the following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the $$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like this${$message} => $mizanSometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.
 
How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP?

preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);
echo $found[1];
 
How can we create a database using PHP and MySQL?

We can create MySQL database with the use of
mysql_create_db(“Database Name”)
 
What are the differences between require and include, include_once and require_once?

The include() statement includes and evaluates the specified file.The documentation below also applies to require(). The two constructs are identical in every way except how they handlefailure. include() produces a Warning while require() results in a Fatal Error. In other words, use require() if you want a missingfile to halt processing of the page.
include() does not behave this way, the script will continue regardless.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only differencebeing that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.include_once() should be used in cases where the same file might be included and evaluated more than once during a particularexecution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
 
Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
 
Yes we can use include() more than one time in any page though it is not a very good practice.

 
What are the different tables present in MySQL, which type of table is generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ?

Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23 and as a result if we do not specify the table name explicitly it will be assigned to the default engine.
 
How can we encrypt the username and password using PHP?
 
The functions in this section perform encryption and decryption, and compression and uncompression:
encryption decryptionAES_ENCRYT() AES_DECRYPT()ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()

Write a select query that will be displayed the duplicated site name and how many times it is duplicated ?

SELECT sitename, COUNT(*) AS NumOccurrences FROM tbl_sites GROUP BY sitename HAVING COUNT(*) > 1

 What does isNaN function do?

 Return true if the argument is not a number.

Symfony http to https

Secure SSL(https) Redirect Filter for Symfony
please follow the steps given below to put up specific page to https or secure url:
1) First add the following settings to your app.yml file:
all:
  ssl:
    insecure_host:    www.avidindiainc.com/blog
    secure_host:      www.avidindiainc.com    
    secure_actions:
      - { module: shop, action: register }
      - { module: shop, action: checkout }
      - { module: register, action: updateCardDetails }

2) Next we add our filter code to lib/sslFilter.class.php (apps/[application name]/lib):

/**
 * Filter for redirecting to SSL for the pages that need it
 *
 * @author Sachin Makwana <sachin@avidindiainc.com>
 * @version 2
 */
class sslFilter extends sfFilter
{
  /**
   * Execute filter
   *
   * @param FilterChain $filterChain The symfony filter chain
   */
  public function execute ($filterChain)
  {
    // Only execute this filter once
    if ($this->isFirstCall() && SF_ENVIRONMENT != 'dev') {
      // Array of modules/actions that require move to SSL
      $ssl_actions = sfConfig::get('app_ssl_secure_actions');

      if (empty($_SERVER['HTTPS']) && count($_POST) < 1) {

        // We're not using SSL and not POSTing data - check if we should be using SSL
        foreach ($ssl_actions as $action) {
          if ($this->getContext()->getModuleName() == $action['module'] && $this->getContext()->getActionName() == $action['action']) {
            $new_url = sprintf('https://%s%s', sfConfig::get('app_ssl_secure_host'), $_SERVER['REQUEST_URI']);
            header('Location: ' . $new_url);
            exit;
          }
        }

        // Using secure host when not required - not good
        if ($_SERVER['HTTP_HOST'] == sfConfig::get('app_ssl_secure_host')) {
          $new_url = sprintf('http://%s%s', sfConfig::get('app_ssl_insecure_host'), $_SERVER['REQUEST_URI']);
          header('Location: ' . $new_url);
          exit;
        }
      } elseif (!empty($_SERVER['HTTPS']) && count($_POST) < 1) {

        // We're using SSL and not posting data
        $dont_redirect = false;
        foreach ($ssl_actions as $action) {
          if ($this->getContext()->getModuleName() == $action['module'] && $this->getContext()->getActionName() == $action['action']) {
            $dont_redirect = true;
          }
        }
        if ($dont_redirect == false) {
          // Redirect
          $new_url = sprintf('http://%s%s', sfConfig::get('app_ssl_insecure_host'), $_SERVER['REQUEST_URI']);
          header('Location: ' . $new_url);
          exit;
        }
      }
    }
    // Next filter
    $filterChain->execute();
  }
}

3) Finally, enable your sslFilter in the application’s config/filters.yml configuration file:

sslFilter:
  class:  sslFilter

Paypal Payments  Using cURL


Pre-requisites:
-cURL
-Paypal Account with API keys and such

vendors/paypal/Paypal.php

<?php /***********************************************************
This File Sets Up Calls to Paypal by arranging url information.
***********************************************************/
class Paypal{
    
    function 
__construct(){
        
    }
    
    function 
DoDirectPayment($paymentInfo=array()){
        
/**
         * Get required parameters from the web form for the request
         */
        
$paymentType =urlencode('Sale');
        
$firstName =urlencode($paymentInfo['Member']['first_name']);
        
$lastName =urlencode($paymentInfo['Member']['last_name']);
        
$creditCardType =urlencode($paymentInfo['CreditCard']['credit_type']);
        
$creditCardNumber urlencode($paymentInfo['CreditCard']['card_number']);
        
$expDateMonth =urlencode($paymentInfo['CreditCard']['expiration_month']);
        
$padDateMonth str_pad($expDateMonth2'0'STR_PAD_LEFT);
        
$expDateYear =urlencode($paymentInfo['CreditCard']['expiration_year']);
        
$cvv2Number urlencode($paymentInfo['CreditCard']['cv_code']);
        
$address1 urlencode($paymentInfo['Member']['billing_address']);
        
$address2 urlencode($paymentInfo['Member']['billing_address2']);
        
$country urlencode($paymentInfo['Member']['billing_country']);
        
$city urlencode($paymentInfo['Member']['billing_city']);
        
$state =urlencode($paymentInfo['Member']['billing_state']);
        
$zip urlencode($paymentInfo['Member']['billing_zip']);
        
        
$amount urlencode($paymentInfo['Order']['theTotal']);
        
$currencyCode="USD";
        
$paymentType=urlencode('Sale');
        
        
$ip=$_SERVER['REMOTE_ADDR'];
        
        
/* Construct the request string that will be sent to PayPal.
           The variable $nvpstr contains all the variables and is a
           name value pair string with & as a delimiter */
        
$nvpstr="&PAYMENTACTION=Sale&IPADDRESS=$ip&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=".$padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1&STREET2=$address2&CITYNAME=$city&STATEORPROVINCE=$state".
        
"&POSTALCODE=$zip&COUNTRY=$country&CURRENCYCODE=$currencyCode";
        
        
/* Make the API call to PayPal, using API signature.
           The API response is stored in an associative array called $resArray */
        
$resArray=$this->hash_call("doDirectPayment",$nvpstr);
        
        
/* Display the API response back to the browser.
           If the response from PayPal was a success, display the response parameters'
           If the response was an error, display the errors received using APIError.php.
           */
        
        
return $resArray;
        
//Contains 'TRANSACTIONID,AMT,AVSCODE,CVV2MATCH, Or Error Codes'
    
}

    function 
SetExpressCheckout($paymentInfo=array()){
        
$amount urlencode($paymentInfo['Order']['theTotal']);
        
$paymentType=urlencode('Sale');
        
$currencyCode=urlencode('USD');
        
        
$returnURL =urlencode($paymentInfo['Order']['returnUrl']);
        
$cancelURL =urlencode($paymentInfo['Order']['cancelUrl']);

        
$nvpstr='&AMT='.$amount.'&PAYMENTACTION='.$paymentType.'&CURRENCYCODE='.$currencyCode.'&RETURNURL='.$returnURL.'&CANCELURL='.$cancelURL;
        
$resArray=$this->hash_call("SetExpressCheckout",$nvpstr);
        return 
$resArray;
    }
    
    function 
GetExpressCheckoutDetails($token){
        
$nvpstr='&TOKEN='.$token;
        
$resArray=$this->hash_call("GetExpressCheckoutDetails",$nvpstr);
        return 
$resArray;
    }
    
    function 
DoExpressCheckoutPayment($paymentInfo=array()){
        
$paymentType='Sale';
        
$currencyCode='USD';
        
$serverName $_SERVER['SERVER_NAME'];
        
$nvpstr='&TOKEN='.urlencode($paymentInfo['TOKEN']).'&PAYERID='.urlencode($paymentInfo['PAYERID']).'&PAYMENTACTION='.urlencode($paymentType).'&AMT='.urlencode($paymentInfo['ORDERTOTAL']).'&CURRENCYCODE='.urlencode($currencyCode).'&IPADDRESS='.urlencode($serverName); 
        
$resArray=$this->hash_call("DoExpressCheckoutPayment",$nvpstr);
        return 
$resArray;
    }
    
    function 
APIError($errorNo,$errorMsg,$resArray){
        
$resArray['Error']['Number']=$errorNo;
        
$resArray['Error']['Number']=$errorMsg;
        return 
$resArray;
    }
    
    function 
hash_call($methodName,$nvpStr)
    {
        require_once 
'constants.php';
        
        
$API_UserName=API_USERNAME;
        
$API_Password=API_PASSWORD;
        
$API_Signature=API_SIGNATURE;
        
$API_Endpoint =API_ENDPOINT;
        
$version=VERSION;
        
        
//setting the curl parameters.
        
$ch curl_init();
        
curl_setopt($chCURLOPT_URL,$API_Endpoint);
        
curl_setopt($chCURLOPT_VERBOSE1);
    
        
//turning off the server and peer verification(TrustManager Concept).
        
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);
        
curl_setopt($chCURLOPT_SSL_VERIFYHOSTFALSE);
    
        
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
        
curl_setopt($chCURLOPT_POST1);
        
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
        //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
        
        
if(USE_PROXY)
            
curl_setopt ($chCURLOPT_PROXYPROXY_HOST.":".PROXY_PORT); 
    
        
//NVPRequest for submitting to server
        
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($version)."&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature).$nvpStr;
    
        
//setting the nvpreq as POST FIELD to curl
        
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
    
        
//getting response from server
        
$response curl_exec($ch);
    
        
//convrting NVPResponse to an Associative Array
        
$nvpResArray=$this->deformatNVP($response);
        
$nvpReqArray=$this->deformatNVP($nvpreq);
    
        if (
curl_errno($ch))
            
$nvpResArray $this->APIError(curl_errno($ch),curl_error($ch),$nvpResArray);
        else 
            
curl_close($ch);
    
        return 
$nvpResArray;
    }
    
    
/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
      * It is usefull to search for a particular key and displaying arrays.
      * @nvpstr is NVPString.
      * @nvpArray is Associative Array.
      */
    
    
function deformatNVP($nvpstr)
    {
    
        
$intial=0;
         
$nvpArray = array();
    
    
        while(
strlen($nvpstr)){
            
//postion of Key
            
$keyposstrpos($nvpstr,'=');
            
//position of value
            
$valuepos strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
    
            
/*getting the Key and Value values and storing in a Associative Array*/
            
$keyval=substr($nvpstr,$intial,$keypos);
            
$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
            
//decoding the respose
            
$nvpArray[urldecode($keyval)] =urldecode$valval);
            
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
         }
        return 
$nvpArray;
    }
}
?>

vendors/paypal/constants.php

<?php /****************************************************
constants.php

This is the configuration file for the samples.This file
defines the parameters needed to make an API call.
****************************************************/

/**
# API user: The user that is identified as making the call. you can
# also use your own API username that you created on PayPal’s sandbox
# or the PayPal live site
*/
define('API_USERNAME''YOUR USERNAME HERE');
/**
# API_password: The password associated with the API user
# If you are using your own API username, enter the API password that
# was generated by PayPal below
# IMPORTANT - HAVING YOUR API PASSWORD INCLUDED IN THE MANNER IS NOT
# SECURE, AND ITS ONLY BEING SHOWN THIS WAY FOR TESTING PURPOSES
*/
define('API_PASSWORD''YOU PASS HERE');
/**
# API_Signature:The Signature associated with the API user. which is generated by paypal.
*/
define('API_SIGNATURE''YOU SIG HERE');
/**
# Endpoint: this is the server URL which you have to connect for submitting your API request.
*/
define('API_ENDPOINT''https://api-3t.paypal.com/nvp'); /**
USE_PROXY: Set this variable to TRUE to route all the API requests through proxy.
like define('USE_PROXY',TRUE);
*/
define('USE_PROXY',FALSE); /**
PROXY_HOST: Set the host name or the IP address of proxy server.
PROXY_PORT: Set proxy port.

PROXY_HOST and PROXY_PORT will be read only if USE_PROXY is set to TRUE
*/
define('PROXY_HOST''127.0.0.1'); define('PROXY_PORT''808');
/* Define the PayPal URL. This is the URL that the buyer is
   first sent to to authorize payment with their paypal account
   change the URL depending if you are testing on the sandbox
   or going to the live PayPal site
   For the sandbox, the URL is
   https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
   For the live site, the URL is
   https://www.paypal.com/webscr&cmd=_express-checkout&token=
   */
define('PAYPAL_URL''https://www.paypal.com/webscr&cmd=_express-checkout&token=');
/**
# Version: this is the API version in the request.
# It is a mandatory parameter for each API request.
# The only supported value at this time is 2.3
*/
define('VERSION''3.0');
?>

components/paypal.php

Component Class:

<?php  <?php  /**
 * Paypal Direct Payment API Component class file.
 */
App::import('Vendor','paypal' ,array('file'=>'paypal/Paypal.php'));
class 
PaypalComponent extends Object{
    
    function 
processPayment($paymentInfo,$function){
        
$paypal = new Paypal();
        if (
$function=="DoDirectPayment")
            return 
$paypal->DoDirectPayment($paymentInfo);
        elseif (
$function=="SetExpressCheckout")
            return 
$paypal->SetExpressCheckout($paymentInfo);
        elseif (
$function=="GetExpressCheckoutDetails")
            return 
$paypal->GetExpressCheckoutDetails($paymentInfo);
        elseif (
$function=="DoExpressCheckoutPayment")
            return 
$paypal->DoExpressCheckoutPayment($paymentInfo);
        else
            return 
"Function Does Not Exist!";
    }
}
?> ?>

sample direct payment controller function:

Controller Class:

<?php  function processPayment(){
     
$paymentInfo = array('Member'=>
                           array(
                               
'first_name'=>'name_here',
                               
'last_name'=>'lastName_here',
                               
'billing_address'=>'address_here',
                               
'billing_address2'=>'address2_here',
                               
'billing_country'=>'country_here',
                               
'billing_city'=>'city_here',
                               
'billing_state'=>'state_here',
                               
'billing_zip'=>'zip_here'
                           
),
                          
'CreditCard'=>
                           array(
                               
'card_number'=>'number_here',
                               
'expiration_month'=>'month_here',
                               
'expiration_year'=>'year_here',
                               
'cv_code'=>'code_here'
                           
),
                          
'Order'=>
                          array(
'theTotal'=>1.00)
                    );

   
/*
    * On Success, $result contains [AMT] [CURRENCYCODE] [AVSCODE] [CVV2MATCH] 
    * [TRANSACTIONID] [TIMESTAMP] [CORRELATIONID] [ACK] [VERSION] [BUILD]
    * 
    * On Fail, $ result contains [AMT] [CURRENCYCODE] [TIMESTAMP] [CORRELATIONID] 
    * [ACK] [VERSION] [BUILD] [L_ERRORCODE0] [L_SHORTMESSAGE0] [L_LONGMESSAGE0] 
    * [L_SEVERITYCODE0] 
    * 
    * Success or Failure is best tested using [ACK].
    * ACK will either be "Success" or "Failure"
    */
 
    
$result $this->Paypal->processPayment($paymentInfo,"DoDirectPayment");
    
$ack strtoupper($result["ACK"]);
                
    if(
$ack!="SUCCESS")
        
$error $result['L_LONGMESSAGE0'];
    else{
        
/* successful do something here! */
    
}
}
?>

Express Checkout Controller Example

Controller Class:

<?php  function _get($var) {
    return isset(
$this->params['url'][$var])? $this->params['url'][$var]: null;
}
    
function 
expressCheckout($step=1){
    
$this->Ssl->force();
    
$this->set('step',$step);
    
//first get a token
    
if ($step==1){
        
// set
        
$paymentInfo['Order']['theTotal']= .01;
        
$paymentInfo['Order']['returnUrl']= "https://fullPathHere/orders/expressCheckout/2/";
        
$paymentInfo['Order']['cancelUrl']= "https://fullPathToCancelUrl";
            
        
// call paypal
        
$result $this->Paypal->processPayment($paymentInfo,"SetExpressCheckout");
        
$ack strtoupper($result["ACK"]);
        
//Detect Errors
        
if($ack!="SUCCESS")
            
$error $result['L_LONGMESSAGE0'];
        else {
            
// send user to paypal
            
$token urldecode($result["TOKEN"]);
            
$payPalURL PAYPAL_URL.$token;
            
$this->redirect($payPalURL);
        }
    }
    
//next have the user confirm
    
elseif($step==2){
        
//we now have the payer id and token, using the token we should get the shipping address
        //of the payer. Compile all the info into the session then set for the view.
        //Add the order total also
        
$result $this->Paypal->processPayment($this->_get('token'),"GetExpressCheckoutDetails");
        
$result['PAYERID'] = $this->_get('PayerID');
        
$result['TOKEN'] = $this->_get('token');
        
$result['ORDERTOTAL'] = .01;
        
$ack strtoupper($result["ACK"]);
        
//Detect errors
        
if($ack!="SUCCESS"){
            
$error $result['L_LONGMESSAGE0'];
            
$this->set('error',$error);
        }
        else {
            
$this->set('result',$this->Session->read('result'));
            
$this->Session->write('result',$result);
            
/*
             * Result at this point contains the below fields. This will be the result passed 
             * in Step 3. I used a session, but I suppose one could just use a hidden field
             * in the view:[TOKEN] [TIMESTAMP] [CORRELATIONID] [ACK] [VERSION] [BUILD] [EMAIL] [PAYERID]
             * [PAYERSTATUS]  [FIRSTNAME][LASTNAME] [COUNTRYCODE] [SHIPTONAME] [SHIPTOSTREET]
             * [SHIPTOCITY] [SHIPTOSTATE] [SHIPTOZIP] [SHIPTOCOUNTRYCODE] [SHIPTOCOUNTRYNAME]
             * [ADDRESSSTATUS] [ORDERTOTAL]
             */
        
}
    }
    
//show the confirmation
    
elseif($step==3){
        
$result $this->Paypal->processPayment($this->Session->read('result'),"DoExpressCheckoutPayment");
    
//Detect errors
        
$ack strtoupper($result["ACK"]);
        if(
$ack!="SUCCESS"){
            
$error $result['L_LONGMESSAGE0'];
            
$this->set('error',$error);
        }
        else {
            
$this->set('result',$this->Session->read('result'));
        }
    }
}
?>

Express Checkout View: express_checkout.ctp

View Template:


<?php 
    
if (!isset($error)){
        if (
$step==2){
            echo 
$form->create('Order',array('type' => 'post''action' => 'expressCheckout/3''id' => 'OrderExpressCheckoutConfirmation')); 
            
//all shipping info contained in $result display it here and ask user to confirm.
            //echo pr($result);
            
echo $form->end('Confirm Payment'); 
        }
        if (
$step==3){
            
//show confirmation once again all information is contained in $result or $error
            
echo '<h2>Congrats</h2>';
        }
    }
    else
        echo 
$error;
?>