Archive for the ‘PHP’ Category



26
Apr

When do you have too much code?

I was integrating a symfony project with Paypal’s Express checkout system last week. Having not messed with this API in several years, I went to Paypal’s site and downloaded their SOAP PHP SDK for integrating with their API. Their scripts work marginally out of the box albeit with terrible documentation. Many classes and functions have zero documentation. Some features of their API have no documentation at all. Anyway, with a little work most people can get a basic working integration with Paypal using their SDK.

In trying to implement several advanced features and callbacks, sifting through hundreds of classes and files in their SDK, I decided that I needed to write my own class. Starting from scratch, I came up with a bare-bones class integrating with the Express checkout API. I completely dumped Paypal’s SOAP implementation in favor of the much simpler NVP (name-value-pair) integration. I don’t see any reason to stick with SOAP on such a simple API. I did include the more advanced features like adding products and shipping (this was probably in Paypal’s, but I couldn’t find it), and shipping and tax callbacks, through the express checkout API. After about 8 hours of coding and testing, I had a working integration that consisted of a handful of files, and about 400 overly spaced lines of code.

I went back and parsed out Paypal’s SDK to see just how large this monster was, and it is over 190,000 lines of code, and just under 1000 individual files.

I had looked at 2 symfony plugins the PaypalDirect and PrestsPaypal plugin, and the both use a lightly stripped version of Paypal’s SDK.

So the point of this is, don’t trust some plugin or package, or script from me, from Paypal, from Symfony, or any provider unless you know it is the best or at least a reasonable way to accomplish your task. Even if the code is cached, the overhead on running 190,000 lines of code every time a customer checks out of your website is simply ridiculous when you can accomplish the same thing with a few hundred. Additionally if you take into account the potential for errors, memory leaks, and security problems with 190,000 lines of code vs. 400, there’s really no comparison.

Now there are times when a huge SOAP integration would be appropriate, but I can’t see how this could possibly be one of those. I also think that if a good programmer started from scratch rather than using Paypal’s bloated code, they could significantly reduce the size of their integration. It’s absolutely baffling trying to debug or get information on a PHP class or method, when there’s 1000 files that you need to hop through to find the piece of code you’re looking for.

7
Oct

Network Merchants API Script

Have just completed a Network Merchants API class. This class utilizes the Network Merchants credit card and electronic check processing API. It also includes the customer vault API which allows merchants to securely store their customer’s credit card and bank account information in Network Merchant’s secure customer vault.

Go to the Network Merchants API PHP Class »

28
Sep

Google chart over HTTPS/SSL

The google charts API does not support the https protocol. If your website is being delivered through a secure connection, the chart will cause a SSL error. Here's a quick way to deliver google chart images over ssl.

To start off with, the chart image must be delivered from a secure connection. Google doesn't allow this plain and simple, so we need to figure out how to host it from our own site. We accomplish this by fetching the image from google using the standard API, writing it to a file, and then calling it on our own script. We basically make a image handling proxy.

Let's take a simple google chart to experiment with.

PHP:
  1. $chart_image = 'http://chart.apis.google.com/chart?chs=500x50&chf=bg,s,ffffff&cht=ls&chd=t:23.52,20.58,26.47,23.52,23.52,23.52,100.00,0.00,23.52,23.52,27.94,20.58,23.52&chco=0066ff';

Next we need to make a function to fetch and save the google chart locally. It will check the chart against the local copy and save it if the chart doesn't exist, or the image has changed. This way we aren't re-writing the same chart on every request, but if the chart changes, it will be updated appropriately.

PHP:
  1. public static function saveImage($chart_url,$path,$file_name){
  2.             if(!file_exists($path.$file_name) || (md5_file($path.$file_name) != md5_file($chart_url)))
  3.             {
  4.                 file_put_contents($path.$file_name,file_get_contents($chart_url));
  5.             }
  6.  
  7.             return $file_name;
  8.     }

Lastly we tie it all together so that it is usable in our application. Im using this within a class, but this could just be used as a function as well. Your image directory will need to be writable for this to work.

PHP:
  1. public function doSomething()
  2. {
  3.  
  4. $local_image_path = '/path/to/images/charts/';
  5. $image_name = 'some_chart_image.png';
  6. $chart_url = 'http://chart.apis.google.com/chart?chs=500x50&chf=bg,s,ffffff&cht=ls&chd=t:23.52,20.58,26.47,23.52,23.52,23.52,100.00,0.00,23.52,23.52,27.94,20.58,23.52&chco=0066ff';
  7.  
  8. $image = self::saveImage($chart_url ,$local_image_path,$image_name);
  9.  
  10. }

You'll need to implement your own error handling, and adjust this to meet the paths and specifics of your server, but the image can now be called from:
<img src="/images/charts/some_chart_image.png" alt="" />

If you need help creating your base chart image, this tool is a great place to start.

10
Aug

Symfony 1.2 redirect specific modules and actions to HTTPS (SSL)

Post Symfony 1.1, the sfSslRequirementPlugin will no longer work.

Having needed a way to force a SSL connection for certain pages, I modified a few scripts that I found online, and created a very simple filter to handle this. This was inspired by this script, and the unacceptably poor example in the Symfony 1.2 book.

To start off with, we need to modify our app.yml file to specify what modules and/or actions need to be secure. Leave the action completely blank if you want the entire module secure. Also change ignore_non_secure to true if you don't care if non specified pages are server over a ssl connection. Basically, from the app.yml below, setting this to false, will redirect any module/action to the non-secure version if it is not specifically defined under secure_actions. Setting it to true will allow a user to request any page over https, even if it is not listed in app.yml. Let me know if this is confusing in any way.

PHP:
  1. //app.yml
  2. all:
  3.   ssl:
  4.     ignore_non_secure: false
  5.     secure_actions:
  6.       - { module: shopping_cart}
  7.       - { module: services  action: apply}

Next we add this filter. Save this under MyProject/apps/MyApp/lib/sfSslFilter.php

PHP:
  1. <?php
  2.  
  3. class sslFilter extends sfFilter
  4. {
  5.     /**
  6.     * Execute filter
  7.     *
  8.     * @param FilterChain $filterChain The symfony filter chain
  9.     */
  10.     public function execute ($filterChain)
  11.     {
  12.  
  13.         $context = $this->getContext();
  14.         $request = $context->getRequest();
  15.  
  16.         $ssl_actions = sfConfig::get('app_ssl_secure_actions');
  17.         $allow_ssl = sfConfig::get('app_ssl_ignore_non_secure');
  18.  
  19.         /*
  20.          * Uncomment For Debugging
  21.          *
  22.          * echo '<pre>';
  23.          * print_r($ssl_actions);
  24.          * echo '</pre>';
  25.          * exit();
  26.          *
  27.          */
  28.  
  29.         if (!$request->isSecure())
  30.         {
  31.             //Redirect to the Secure Url
  32.             //If the module and/or action match $ssl_actions set in app.yml
  33.             foreach($ssl_actions as $action)
  34.             {
  35.  
  36.                if($action['module'] == $context->getModuleName() && !$action['action']){
  37.  
  38.                     //The entire module needs to be secure
  39.                     //Redired no matter what the action is.
  40.  
  41.                     $secure_url = str_replace('http', 'https', $request->getUri());
  42.                     return $context->getController()->redirect($secure_url, 0 , 301);
  43.  
  44.  
  45.                 } else if($action['module'] == $context->getModuleName() && $action['action'] == $context->getActionName())
  46.                 {
  47.  
  48.                     //Redirect if the module and action need to be secure
  49.  
  50.                     $secure_url = str_replace('http', 'https', $request->getUri());
  51.                     return $context->getController()->redirect($secure_url, 0 , 301);
  52.                 }
  53.              }
  54.  
  55.         } else if($request->isSecure() && !$allow_ssl)
  56.         {
  57.             $redirect = true;
  58.  
  59.             //Redirect to the Non-Secure Url
  60.             //If the module and/or action are not in $ssl_actions set in app.yml
  61.             foreach($ssl_actions as $action)
  62.             {
  63.                 if(($action['module'] == $context->getModuleName() && !$action['action']) || ($action['module'] == $context->getModuleName() && $action['action'] == $context->getActionName()))
  64.                 {
  65.                     $redirect = false;
  66.                 }
  67.             }
  68.  
  69.             if($redirect)
  70.             {
  71.                  $non_secure_url = str_replace('https', 'http', $request->getUri());
  72.                  return $context->getController()->redirect($non_secure_url, 0 , 301);
  73.             }
  74.         }
  75.  
  76.         $filterChain->execute();
  77.  
  78.     }
  79. }

Finally, add to the MyProject/apps/MyApp/config/filters.yml file:

PHP:
  1. sslFilter:
  2.   class:  sslFilter

Clear the cache (symfony cc), and there you have it. Let me know if you have a better or different way of dealing with this on a per-module or per-action basis. Hopefully sfSslRequirementPlugin will get ported to work with Symfony 1.2, as the method above will not alter routes on your application.

Additionally, I specifically used 301 redirects to make this more search engine friendly, in case Google or another bot gets on a ssl page. This will help prevent getting duplicate pages indexed due to http and https versions of the same page.

6
Aug

20 Great non-PHP Tools for PHP Developers

By nature I always strive to find more efficient, and better ways to perform tasks. There are a number of development tools that I use that really help me develop better applications in a reduced amount of time. These are the tools I use every day for web development.
Click to continue...

28
Jul

PHP Magic __get, __set Methods, and Retaining Private and Protected Properties

I have been making an integration with a complex API with hundreds of potential user provided variables, necessitating me use of PHP's Magic __get and __set methods.

Unfortunately, by using these methods, PHP's restriction on private and protected properties is bypassed, making all properties public. This is completely unacceptable from my coding perspective.

This class model overrides the magic __get and __set's ability to alter and access private and protected properties. Public properties are unaffected. This script also allows the class to set and access private and protected properties.

PHP:
  1. <?php
  2.  
  3. class setter_getter_respect
  4. {
  5.    
  6.     private $current_page;
  7.     private $private_properties = array();
  8.    
  9.     public function __construct()
  10.     {
  11.        
  12.         $class = new ReflectionClass(__CLASS__);
  13.         $this->current_page = $class->getFileName();
  14.        
  15.         $class_properties = get_class_vars(__CLASS__);
  16.        
  17.         foreach($class_properties as $class_property_name => $property_value)
  18.         {
  19.             $prop = new ReflectionProperty(__CLASS__, $class_property_name);
  20.            
  21.             if($prop->isPrivate() || $prop->isProtected())
  22.             {
  23.                 $this->private_properties[$prop->getName()] = ($prop->isPrivate()) ? 'private' : 'protected';
  24.             }
  25.         }
  26.     }
  27.    
  28.     public function __set($var, $val)
  29.     {
  30.         $requesting_page = debug_backtrace();
  31.        
  32.         if(($requesting_page[0]['file'] != $this->current_page) && (array_key_exists($var,$this->private_properties)))
  33.         {
  34.  
  35.             trigger_error("Cannot access ".$this->private_properties[$var]." property ".__CLASS__."::".$var." in ".$requesting_page[0]['file']."on line ". $requesting_page[0]['line'],E_USER_ERROR);
  36.  
  37.         }
  38.            
  39.         $this->$var = $val;
  40.     }
  41.    
  42.     public function __get($var)
  43.     {
  44.        
  45.         $requesting_page = debug_backtrace();
  46.        
  47.         if(isset($this->$var)){
  48.            
  49.             if(($requesting_page[0]['file'] != $this->current_page) && (array_key_exists($var,$this->private_properties)))
  50.             {
  51.  
  52.                 trigger_error("Cannot access ".$this->private_properties[$var]." property ".__CLASS__."::".$var." in ".$requesting_page[0]['file']."on line ". $requesting_page[0]['line'],E_USER_ERROR);
  53.  
  54.             }
  55.            
  56.             return $this->$var;
  57.            
  58.         } else {
  59.            
  60.             throw new Exception("Required property [" . $var . "] has not been set!");
  61.                
  62.         }
  63.     }
  64. }
  65.  
  66. ?>

Extended classes will not have access to __get or __set protected properties. I will alter this snippet when I find a suitable method of handling extended classes.

I'm hoping that php alters the way it handles private and protected properties through the magic methods but until then, this is a way to semi-preserve private and protected properties.

27
Jul

US States Snippet and SQL Dump

Here's some US states snippets. Included are php arrays, and a MySQL states dump...

Click to continue...

25
Jul

PHP – Script benchmark / bottleneck debugging snippet

Here's a really simple function that I use for finding bottlenecks in php scripts. You can add any number of steps to the the script using the microtime() function, and this function shows the execution time of each step.

PHP:
  1. /**
  2. * Benchmark a php script
  3. *
  4. * @param array $time_sample
  5. * @return string HTML
  6. */
  7. function quick_benchmark($time_sample = array())
  8. {
  9.     $steps = count($time_sample);
  10.     $output = '';
  11.    
  12.     for($i=0;$i<$steps;$i++)
  13.     {
  14.         if($i<($steps-1))
  15.         {
  16.             $output .= '<p>Time '. ($i+1) .': '. number_format(($time_sample[$i+1] - $time_sample[$i]),6,'.','') .' seconds.</p>';
  17.         }
  18.     }
  19.    
  20.     $output .= '<p>Total time: '. number_format(($time_sample[$steps-1] - $time_sample[0]),6,'.','') .' seconds.</p>';
  21.    
  22.     return $output;
  23. }

This is a simple example using sleep() to demonstrate the output.

PHP:
  1. $time_sample[] = microtime(true); //start
  2. sleep(1);
  3. $time_sample[] = microtime(true); //time 1
  4. sleep(2);
  5. $time_sample[] = microtime(true); //time 2
  6. sleep(3);
  7. $time_sample[] = microtime(true); //time 3
  8. sleep(1);
  9. $time_sample[] = microtime(true); //time 4
  10.  
  11. echo quick_benchmark($time_sample);

The script outputs:

Time 1: 1.001833 seconds.
Time 2: 2.001427 seconds.
Time 3: 3.001124 seconds.
Time 4: 1.001720 seconds.
Total time: 7.006104 seconds.

It's a good idea to comment each time you record a microtime so that you know which section of script took that amount of time.

24
Jul

PHP – Random string generator snippet

This is a little function that I use all the time to generate random strings. There are 3 options for random strings with this: Alpha, Alpha-numeric, and Alpha-numeric with symbols. This is important because sometimes it's a good idea not to allow special characters in a php string. However, the special characters are great if you need to create a key or initialization vector for 2 way encryption.

This can be used to generate random passwords or keys or just about anything else that needs a random string. You can also throw this directly into a class and use it as a static method.

PHP:
  1. /**
  2. * Generate a random string
  3. *
  4. * @param int $length
  5. * @param int $mode 1 = Alpha, 2 = Alpha-numeric, 3 = Alpha-numeric with symbols
  6. * @param boolian $char_set Set true for Upper and Lower case letters
  7. * @return string
  8. */
  9. function random_string($length=16,$mode=1,$char_set=false)
  10. {
  11.     $string = '';
  12.     $possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  13.    
  14.     if($char_set) {
  15.    
  16.         $possible .= strtolower($possible);
  17.    
  18.     }
  19.    
  20.     switch($mode) {
  21.        
  22.         case 3:
  23.            
  24.             $possible .= '`~!@#$%^&*()_-+=|}]{[":;<,>.?/';
  25.            
  26.         case 2:
  27.        
  28.             $possible .= '0123456789';
  29.             break;
  30.            
  31.     }
  32.    
  33.     for($i=1;$i<$length;$i++) {
  34.         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
  35.         $string .= $char;
  36.     }
  37.    
  38.     return $string;
  39. }

Examples:

PHP:
  1. echo random_string(32);
  2. //WQTISVJVMWSEFXEIQISJPCBENFEHQAN

PHP:
  1. echo random_string(16,2,true);
  2. //cZhVGHJb0PqJIk3

PHP:
  1. echo random_string(16,3);
  2. //=,:UT__GN[ST>GH

10
Jul

PHP AES Encryption

Sometime it's needed to use 2 way encryption for storing data. I've been using an AES encryption class for a little over a year now, and it is an excellent way to use FIPS Compliant AES encryption in php. The script comes in a free version (ECB mode only) and a paid version for only $10.

This is a completely standalone class that does not require the mcrypt library, and has php4 and php5 support. Encryption is available in 128, 192, and 256 bit, depending on the cipher length.

Using it is easy as this:

PHP:
  1. include("AES.class.php");
  2.  
  3. $my_256_key = 'MpDsw*8cQM&fez*7eBoZB^W*kP652NoW';
  4. $initialization_vector = 'WmR&z28zWn8r*9$R';
  5.  
  6. $aes = new AES($my_256_key, "CBC", $initialization_vector);
  7.  
  8. $string_to_encrypt = 'SOME STRING OF TEXT, OR EVEN AN ENTIRE FILE';
  9.  
  10. $encrypted_string = $aes->encrypt($string_to_encrypt);
  11.  
  12. $original_string = $aes->decrypt($encrypted_string);

The cipher modes that are supported are: Electronic Codebook (ECB), Cipher Block Chaining (CBC), Cipher Feedback (CFB), and Output Feedback (OFB). --Block Cipher Modes »

If you are needing to integrate real encryption into a script, I highly recommend this class. It's strong enough for storing sensitive data like credit cards (key management is another topic), and has an extremely easy interface.

Keep in mind that encryption is only as secure as the key and the key management that is used. Unlike using hash functions (Md5, SHA1), encryption can be reversed, and will considerably slow down a php script, especially so for encrypting large amounts of data.

Database Storage:
I would recommend base 64 encoding an encrypted string and then storing in a text or blob type field. Output from AES encryption will likely be corrupted by a database's character encoding if you do not.

Copyright © 2010 SayNoToFlash, Jamie Estep, All Rights Reserved · Theme design by Themes Boutique