Category Archives: PHP

php news, php articals, php certification, php frameworks, php classes, php code, php feed, php update, php array, php string, php function, php oops, php xml, php open projects, PHP SOAP

How to convert PHP object to Array?

I created a function to convert PHP Object to Array.
The main function remove unnecessary data from the object.
Second loop gives you straight array. You can manipulate it as you want to display PHP Array data.


function phpObjectToArray($phpObject)
{
    if(!is_object($phpObject) && !is_array($phpObject))
        return $phpObject;

    $phpArray=array();
    foreach($phpObject as $member=>$data)
    {
        $phpArray[$member]=phpObjectToArray($data);

    }
    return $phpArray;
}

$scopeArray = phpObjectToArray($show_scope_data);

echo"
";
print_r($scopeArray);

Output after passing object. 

Array
(
    [0] => Array
        (
            [data] => Array
                (
                    [ekey] => 1
                    [ecode] => UNKNOWN
                    [ename] => Unknown Name
                    [edesc] => Name has an unknown scope
                    [flag] => 1
                )

        )

    [1] => Array
        (
            [data] => Array
                (
                    [ekey] => 2
                    [ecode] => GLOBAL
                    [ename] => This Scope Name
                    [edesc] => Name applies to all sites
                    [flag] => 1
                )

        )

    [2] => Array
        (
            [data] => Array
                (
                    [ekey] => 3
                    [ecode] => PHPMIND
                    [ename] => PHPMIND Scope Name
                    [edesc] => PHPMIND applies to all tuto
                    [flag] => 1
                )

        )

    [3] => Array
        (
            [data] => Array
                (
                    [ekey] => 4
                    [ecode] => PHP Technology
                    [ename] => PHP Technology Scope Name
                    [edesc] => PHP Technology applies to all tuto
                    [flag] => 1
                )

        )

    [4] => Array
        (
            [data] => Array
                (
                    [ekey] => 5
                    [ecode] => CSS2
                    [ename] => CSS2 Scope Name
                    [edesc] => CSS2 applies to all css2 tuto
                    [flag] => 1
                )

        )

    [5] => Array
        (
            [data] => Array
                (
                    [ekey] => 6
                    [ecode] => HTML5
                    [ename] => HTML5 Scope Name
                    [edesc] => HTML5 Name applies to a HTML5 tuto
                    [flag] => 1
                )

        )

)

$array_list = array();

foreach($scopeArray  as $key=>$value)
{
    $array_list[$key]= $scopeArray[$key]["data"];
}

print_r($array_list);

Last print_r() function will display normal array.

Share

How to convert PHP array in diffrent kind of json objects?

JSON objects are used everywhere and very easy to implement.
Thanks to PHP it has inbuilt function but if you want different kind of json object which is possible based on requirement. In my case i wanted to use
var availableTags = [{“key”:1,”value”:”AERO 1″},{“key”:2,”value”:”AERO 3″},{“key”:3,”value”:”AIR CANADA 4″},{“key”:6,”value”:”AIR CANADA 26″},{“key”:7,”value”:”AIR CANADA JAZZzzz”}];

if have key value pair of array json_encode($yourArray) will not return
above format!

Well that was my requirement, yours could be different but here is the solution.
You can tweak little bit and ready to go!

 $value)
{
   if(empty($key) && empty($value))
   {
	  continue;
    }
	$temAccNameArray[] = array('key' => $key,'value'=>$value);
}
echo json_encode($temAccNameArray);
?>;
Share

PHP Paypal Recurring PayPro Flow

I spend several day to figure our Paypal Recurring PayPro Flow Payment API.
But finally managed to create something cool with a class. I would like to share with you guys.

Why Paypal Recurring PayPro Flo ?
Companies want to charge there customers on monthly basics for different services that’s why its called Recurring. With PayPro Flow Payment API it become smooth and as a advantage user/customer does not leave site while making payment. Paypal will charge you $30 per month to create this account with PayPro Flow Payment system. https://manager.paypal.com/ This is where you can see everything related to your account.
In order to activate Recurring you need to make phone call to Paypal account manger and request them to enable Recurring then only it will work.

Code and examples –
This class “PayFlowTransaction.class.php” have everything you need.
Apart from that there is one more file, which you will be using to pass your form variables and it will show you result. So called instance!

What you can do with this class and code –
1. Create Recurring Billing Profile
2. Modify – Recurring Billing Amount and CC detials or anything
3. Reactivate – Reactivate Cancelled profile.
4. Cancel – You can cancel profile anytime
5. Inquiry – Details of each payment for a profile and Status of a customer’s profile
6. Payment – Retry a previously failed payment
You have to just pass correct variable and look litte bit in this documentation https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_PayflowPro_RecurringBilling_Guide.pdf
In order to see this code in action you need to have your own account.

$txn->PARTNER = ‘PayPal’; // this is default
$txn->USER = ‘your_username’;
$txn->PWD= ‘You_should_ask_to_admin’;
$txn->VENDOR = ‘yourvendername_checkwith_your_admin’; //$txn->USER; //or your vendor name

PayFlowTransaction.class.php


load_config();
  
  
 }
 
 public function load_config() {
  
  if ( defined('PAYFLOWPRO_USER') ) {
   $this->data['USER'] = constant('PAYFLOWPRO_USER');
  }
  
  if ( defined('PAYFLOWPRO_PWD') ) {
   $this->data['PWD'] = constant('PAYFLOWPRO_PWD');
  }

  if ( defined('PAYFLOWPRO_PARTNER') ) {
   $this->data['PARTNER'] = constant('PAYFLOWPRO_PARTNER');
  }
  
  if ( defined('PAYFLOWPRO_VENDOR') ) { 
   $this->data['VENDOR'] = constant('PAYFLOWPRO_VENDOR');
  }
  else {
   if ( isset($this->data['USER']) ) {
    $this->data['VENDOR'] = $this->data['USER'];
   }
   else {
    $this->data['VENDOR'] = null;
   }
  }
  
 }
 
 public function __set( $key, $val ) {
  
  $this->data[$key] = $val;
  
 }
 
 public function __get( $key ) {
  
  if ( isset($this->data[$key]) ) {
   return $this->data[$key];
  }
  
  return null;
 }
 
 public function get_gateway_url() {
  
  if ( strtolower($this->environment) == 'live' ) {
   return $this->gateway_url_live;
  }
  else {
   return $this->gateway_url_devel;
  }
  
 }
 
 public function get_data_string() {
  
  $query = array();

  if ( !isset($this->data['VENDOR']) || !$this->data['VENDOR'] ) {
 $this->data['VENDOR'] = $this->data['USER'];
  }

  
  foreach ( $this->data as $key => $value) {
   
   if ( $this->debug ) {
    echo "{$key} = {$value}
";
   }
   
   $query[] = strtoupper($key) . '[' .strlen($value).']='.$value;
  }
  
  return implode('&', $query);
  
 }

 public function before_send_transaction() {
  
  $this->txn_successful = false;
  $this->raw_response = null; //reset raw result
  $this->response_arr = array();
 } 
 
 public function reset() {
  
  $this->txn_successful = null;
  $this->raw_response = null; //reset raw result
  $this->response_arr = array();
  $this->data = array();
  $this->load_config();
 } 
 
 
 public function send_transaction() {
  
  try { 
   
   $this->before_send_transaction();
    
   $data_string = $this->get_data_string();
   
      $headers[] = "Content-Type: text/namevalue"; //or text/xml if using XMLPay.
      $headers[] = "Content-Length: " . strlen ($data_string);  // Length of data to be passed 
      $headers[] = "X-VPS-Timeout: {$this->vps_timeout}";
      $headers[] = "X-VPS-Request-ID:" . uniqid(rand(), true);
   $headers[] = "X-VPS-VIT-Client-Type: PHP/cURL";          // What you are using
   
   $headers = array_merge( $headers, $this->headers );
 
   if ( $this->debug ) {
    echo  __METHOD__ . ' Sending: ' . $data_string . '
';
   }
 
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $this->get_gateway_url() );
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
      curl_setopt($ch, CURLOPT_HEADER, 1);                // tells curl to include headers in response
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        // return into a variable
      curl_setopt($ch, CURLOPT_TIMEOUT, 90);              // times out after 90 secs
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);        // this line makes it work under https
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);        //adding POST data
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);       //verifies ssl certificate
      curl_setopt($ch, CURLOPT_FORBID_REUSE, TRUE);       //forces closure of connection when done
      curl_setopt($ch, CURLOPT_POST, 1);          //data sent as POST
 
   $i = 0;
 
      while ($i++ <= $this->gateway_retries) {
          
          $result = curl_exec($ch);
          $headers = curl_getinfo($ch);
 
          if (array_key_exists('http_code', $headers) && $headers['http_code'] != self::HTTP_RESPONSE_OK) {
              sleep($this->gateway_retry_wait);  // Let's wait to see if its a temporary network issue.
          }
          else  {
              // we got a good response, drop out of loop.
              break;
          }
      }  

      if ( !array_key_exists('http_code', $headers) || $headers['http_code'] != self::HTTP_RESPONSE_OK ) {
    throw new InvalidResponseCodeException;
      }

   $this->raw_response = $result;
   
   $result = strstr($result, "RESULT");
   $ret = array();

      while( strlen($result) > 0 ){

          $keypos = strpos($result,'=');
          $keyval = substr($result,0,$keypos);
 
          // value
          $valuepos = strpos($result,'&') ? strpos($result,'&'): strlen($result);
          $valval = substr($result,$keypos+1,$valuepos-$keypos-1);

          // decoding the respose
          $ret[$keyval] = $valval;
        
          $result = substr($result, $valuepos+1, strlen($result) );
      }
      
   return $ret;
  }
  catch( Exception $e ) {
   @curl_close($ch);
   throw $e;
  }
 }
 
 public function response_handler( $response_arr ) {
 
  try { 
      $result_code = $response_arr['RESULT']; // get the result code to validate.
  
   if ( $this->debug ) {
    echo __METHOD__ . ' response=' . print_r( $response_arr, true) . '
';
    echo __METHOD__ . ' RESULT=' . $result_code . '
';
   }
   
   if ( $result_code == 0 ) {

    //
    // Even on zero, still check AVS
    //
          
          if ( $this->avs_addr_required ) {
     $err_msg = "Your billing (street) information does not match.";
           
           if ( isset($response_arr['AVSADDR'])) {
                if ($response_arr['AVSADDR'] != "Y") {
              throw new AVSException( $err_msg  );
                }
              }
              else {
               if ( $this->avs_addr_required == 2 ) {
              throw new AVSException( $err_msg );
               }
              }
          }
  
    if ( $this->avs_zip_required ) {
  
              $err_msg = "Your billing (zip) information does not match. Please re-enter.";
  
           if (isset($nvpArray['AVSZIP'])) {
               if ($nvpArray['AVSZIP'] != "Y") {
       throw new AVSException( $err_msg );
               }
              }
              else {
               if ( $this->avs_zip_required == 2 ) {
              throw new AVSException( $err_msg );
               }
               
              }
          }
          
          if ( $this->require_cvv2_match ) {
  
     $err_msg = "Your card code is invalid. Please re-enter.";
           
           if ( array_key_exists('CVV2MATCH', $response_arr) ) {
               if ($response_arr['CVV2MATCH'] != "Y") {
                   throw new CVV2Exception( $err_msg );
               }
              }
              else {
               if ( $this->require_cvv2_match == 2 ) {
              throw new CVV2Exception( $err_msg );
               }
              }
          }
  
    //
    // Return code was 0 and no AVS exceptions raised
    //
    $this->txn_successful = true;
    
    parse_str($this->raw_response, $this->response_arr);
    return $this->response_arr;
      }
      else if ($result_code == 1 || $result_code == 26) {
    throw new InvalidCredentialsException( "Invalid API Credentials" );
      }
      else if ($result_code == 12) {
          // Hard decline from bank.
          throw new TransactionDataException( "Your transaction was declined." );
      }
      else if ($result_code == 13) {
          // Voice authorization required.
          throw new TransactionDataException ("Your Transaction is pending. Contact Customer Service to complete your order.");
      }
      else if ($result_code == 23 || $result_code == 24) {
          // Issue with credit card number or expiration date.
         $msg = 'Invalid credit card information: ' . $response_arr['RESPMSG'];
         throw new TransactionDataException ($msg);
      }
  
      // Using the Fraud Protection Service.
      // This portion of code would be is you are using the Fraud Protection Service, this is for US merchants only.
      if ( $this->fraud_protection ) {
  
          if ($result_code == 125) {
              // 125 = Fraud Filters set to Decline.
              throw new FraudProtectionException ( "Your Transaction has been declined. Contact Customer Service to place your order." );
          }
          else if ($result_code == 126) {
              throw new FraudProtectionException ( "Your Transaction is Under Review. We will notify you via e-mail if accepted." );
          }
          else if ($result_code == 127) {
     throw new FraudProtectionException ( "Your Transaction is Under Review. We will notify you via e-mail if accepted." );
          }
      }
      
      //
      // Throw generic response
      //
      throw new FuseException( $response_arr['RESPMSG'] );
      
      
  }
  catch( Exception $e ) {
   throw $e;
  }
   
 } 

 public function process() {
 
  try { 
   return $this->response_handler($this->send_transaction());
  }
  catch( Exception $e ) {
   throw $e;
  }
 
 }

 public function apply_associative_array( $arr, $options = array() ) {
  
  try { 
   
   $map_array = array();
     
   if ( isset($options[self::KEY_MAP_ARRAY]) ) {
    $map_array = $options[self::KEY_MAP_ARRAY];
   }
  
   foreach( $arr as $cur_key => $val ) {

    if( isset($map_array[$cur_key]) ) {
     $cur_key = $map_array[$cur_key];
    }
    else {
     if ( isset($options['require_map']) && $options['require_map'] ) {
      continue;
     }
    }
    
    $this->data[strtoupper($cur_key)] = $val;
   
   }
  }
  catch( Exception $e ) {
   throw $e;
  }
  
 }
 
 
}


// Added by me 


class FuseException extends Exception {
 
}
//

class InvalidCredentialsException extends Exception {
 
}

class GatewayException extends Exception {
 
}

class InvalidResponseCodeException extends GatewayException {
 
}


class TransactionDataException extends Exception {
 
} 

class AVSException extends TransactionDataException {
 
}

class CVV2Exception extends TransactionDataException {
 
}

class FraudProtectionException extends Exception {

}

?>

PayFlowTransaction-action.php

PARTNER = 'PayPal'; 
   $txn->USER = 'APIwebsite';
   $txn->PWD= 'You_should_ask_to_admin';
   $txn->VENDOR = 'yourvendername_checkwith_your_admin'; //$txn->USER; //or your vendor name
 

    //
   // transaction information
   //

	// To Perform Recurring Tasks  START 
    $txn->TRXTYPE='R'; // 
    $txn->ACTION='A'; // Specifies Add (A), Modify (M), Cancel (C), Reactivate (R), Inquiry (I), or Payment (P) (To - Retry a previously failed payment).
    $txn->PROFILENAME='phpmindSubscription'; //  Name for the profile (user-specified). Can be used to search for a profile. Non-unique identifying text name
    
    $tomorrow = date('mdY',mktime()+86400);
    
    $txn->START=$tomorrow; 
    // $txn->START=date("mdY");   // Beginning date for the recurring billing cycle used to calculate when payments should be made. Use tomorrow’s date or a date in the future. Format: MMDDYYYY
    $txn->PAYPERIOD='MONT'; // Specifies how often the payment occurs:  MONT: Monthly, FRWK: Every Four Weeks, QTER: Quarterly
    $txn->TERM='0';  // A value of 0 means that payments should continue until the profile is deactivated. Or specfiy number 
    // $txn->OPTIONALTRX='S'; // S: a Sale transaction for an initial fee specified by OPTIONALTRXAMT. Defines an optional Authorization for validating the account information or for charging an initial fee. If this transaction fails, then the profile is not generated
    //$txn->OPTIONALTRXAMT='2.00';
    $txn->COMMENT1= $_SESSION['username'];  // (Optional) Merchant-defined value for reporting and auditing purposes. Limitations: 128 alphanumeric characters
    $txn->COMMENT2= $COMMENT2; // In my case selected plan :::  (Optional) Merchant-defined value for reporting and auditing purposes. Limitations: 128 alphanumeric characters
    $txn->RECURRING ='Y';
    $txn->COMPANYNAME = $_SESSION['username']."__".$_SESSION['item_description'];
    ///////////////////////  // To Perform Recurring Tasks  END

     $txn->TENDER = 'C'; //sets to a cc transaction P for paypal
     $txn->ACCT = $ccn; //cc number
     // $txn->TRXTYPE = 'S'; //txn type: sale
     $txn->AMT = $amount; //amount: 1 dollar
     $txn->EXPDATE= $exp1.substr($exp2, -2); //4 digit expiration date
     $txn->CVV2=$cvv;
   
     $txn->FIRSTNAME = $fname;
     $txn->LASTNAME = $lname;
     $txn->STREET = $address;
     $txn->CITY = $city;
     $txn->COUNTRY = $country;
     $txn->STATE = $state;
     $txn->ZIP = $zip;
     $txn->EMAIL = $email;
  
  
   //$txn->debug = true; //uncomment to see debugging information
   //$txn->avs_addr_required = 1; //set to 1 to enable AVS address checking, 2 to force "Y" response
   //$txn->avs_zip_required = 1; //set to 1 to enable AVS zip code checking, 2 to force "Y" response
   //$txn->cvv2_required = 1; //set to 1 to enable cvv2 checking, 2 to force "Y" response
   //$txn->fraud_protection = true; //uncomment to enable fraud protection


   $txn->process();
   
   //echo "success: " . $txn->txn_successful;
   //echo "response was: ";
   //echo "
";
   // print_r($txn->response_arr);   

  }
  catch( TransactionDataException $tde ) {
   echo 'bad transaction data ' . $tde->getMessage();
        }
        catch( InvalidCredentialsException $e ) {
   echo 'Invalid credentials';
  }
  catch( InvalidResponseCodeException $irc ) {
   echo 'bad response code: ' . $irc->getMessage();
  }
  catch( AVSException $avse ) {
   echo 'AVS error: ' . $avse->getMessage();
  }
  catch( CVV2Exception $cvve ) {
   echo 'CVV2 error: ' . $cvve->getMessage();
  }
  catch( FraudProtectionException $fpe ) {
   echo 'Fraud Protection error: ' . $fpe->getMessage();
  }
        catch( Exception $e ) {
   echo $e->getMessage();
  }
         
?>

Code above is very easy to understand.

//ini_set('display_errors', 1);
//ini_set('log_errors', 1);
//ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
// error_reporting(E_ALL);

this is to show error if you have any.
and rest of them are variables.

Hope it will cut down your development time.

Share

How to merge two mysql query results into one array?

You can use UNION operator to merge the result-set of two or more SELECT statements into one array.
The default behavior for UNION is that duplicate rows are removed from the result. UNION ALL does not remove duplicate.

There are few things need to be kept in mind.

A. SELECT statement within the UNION must have the same number of columns.
B. The field should have similar data types.
C. Fields in each SELECT statement must be in the same order if not make them.
D. If column have diffrent name make column another name by using an alias with “AS” kewords as given in the example

SELECT column1 AS alias_name FROM table

Here is the full example of UNION.


	  $select_btemp_1 = "SELECT * FROM table1 WHERE enable='1' AND aid='1'";

	  $select_btemp_2 = "SELECT * FROM table1 WHERE enable='1' AND user_id='$user_id' ORDER BY  aid ASC";

	  $select_btemp =  $select_btemp_1." ".UNION." ".$select_btemp_2;

	  $btemp_query = mysql_query($select_btemp);
	  $btemp_count = mysql_num_rows($btemp_query);

	  if($btemp_count > 0)
	  {
		while($row_images = mysql_fetch_array($btemp_query))
		{ 	
			echo $row_images[temp_desc];	
		}
	  }

	
Share

PHP: How to dynamically resize image in your page?

Every php programmer/developer have to resize images in web pages.
There are a lot of ways available through JavaScript, jQuery and PHP.
Here is very simple way to resize image temporarily but proportionally.
You can still keep big image file in you in your folder but when you are displaying you can make is smaller.

Jquery and java script some times does not work. So PHP way is very useful.


 ($inputwidth/$inputheight)) {
            $outputwidth = $inputwidth;
            $outputheight = ($inputwidth * $height)/ $width;
        }

        elseif (($width/$height) < ($inputwidth/$inputheight)) {
            $outputwidth = ($inputheight * $width)/ $height;
            $outputheight = $inputheight;
        }

        elseif (($width/$height) == ($inputwidth/$inputheight)) {
            $outputwidth = $inputwidth;
            $outputheight = $inputheight;
            }

echo '';

?>
Share

How to save remote image in server or save image from a url?

Saving images from any live url is very easy with php.
Here are three ways to do this.
1. Using Curl
2. Using File functions
3. Using GD library functions.

Condition is in your server php.ini should have “allow_url_fopen” On. check you php setting using phpinfo() function.

Create a folder name “images_saved” to save your images.

Using Curl

Image ' . basename($i) . ' Downloaded Successfully';
    }else{
        echo '

Image ' . basename($i) . ' Download Failed

'; } } function image_save_from_url($my_img,$fullpath){ if($fullpath!="" && $fullpath){ $fullpath = $fullpath."/".basename($my_img); } $ch = curl_init ($my_img); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); $rawdata=curl_exec($ch); curl_close ($ch); if(file_exists($fullpath)){ unlink($fullpath); } $fp = fopen($fullpath,'x'); fwrite($fp, $rawdata); fclose($fp); } ?>

Using File functions


Using GD library functions.


Share

How to filter bad words?

You can use this simple function to filter bad words.

Please see attachment for mysql table of frequently used 458 bad words. http://www.phpmind.com/codedemo/php-bad-word-filter/bad_word.txt.zip
You can add more word easily as you know more!!


  function bad_wordcensor($txt)
  {
    $q = mysql_query("SELECT bad_word, replacement FROM bad_words");
    while ($row_bad = mysql_fetch_array($q))
    {
      $txt = str_ireplace($row_bad['bad_word'], $row_bad['replacement'], $txt);
    }

  return $txt;
  }

echo bad_wordcensor($_POST["comments"]);
Share

How to get IP address through php code.

Every php coder want to store IP address of user for tracking and other different purpose.

Here is the function which i am using in my code to store ip address in db.

    function userIPAdd()
    {
       //This returns the True IP of the client calling the requested page
       // Checks to see if HTTP_X_FORWARDED_FOR
       // has a value then the client is operating via a proxy
       $userIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
       if($userIP == "")
      { 
         $userIP = $_SERVER['REMOTE_ADDR'];  
      }
      // return the IP we've figured out:
      return $userIP;
    }

You can use this simple php function in different ways.

Share

Display PHP Errors When Display_errors Is Disabled

When Display_errors is off in php.ini it is hard to see where the bug is!

While you are working in server where display errors are off you can add this code on top of the page and it will show whats going on in your php code.

ini_set('display_errors', 1);
 ini_set('log_errors', 1);
 ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
 error_reporting(E_ALL);

I prefer to use this code through a function or include file and when you are done you can close or disable.

Share