Pages

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Friday, July 6, 2012

OAuth - Cross-Site Authentication

Nowadays its normal for users to PUSH/PULL data TO/FROM 3rd party Web Applications to your Website.
eg: Facebook LIKE button

USE CASE
1.     A User (or You on behalf of the User) wants to login to their account
        on a 3rd party Web Application and pass data to your Web Application?
eg:  Tweet from your website using their twittername
       Check their Gmail from your website

QUESTION:
Can a user submit their Login Credentials via your WebApp and expect you to securely handle their Sensitive Data?
How does your Web App Authorise & Store their Login Credentials?
How does your website make Requests based on Their Login Credentials?

ANSWER:
OAuth v1 or v2

WIth an OAuth Client connecting to an OAuth Server, we can solve the above USE CASE.



Study the above Diagram for an Overview of OAuth v1

When you're ready to connect to 3rd party Web Apps...read their DOcumentation of their implementation of OAuth since methods and names may change.

Client Side implementation of OAuth

With Browser side code you have no way of PREVENTING people from seeing your Secret 'oauth_consumer_key' and 'oauth_toke_secret'.
StackOverFlow.com Article  StackOverFlow Article 2
Read the following Very Interesting Article for some ideas to solve Client Side OAuth implementation Security Problems. http://derek.io/blog/2010/how-to-secure-oauth-in-javascript/

Note:
You should also understand
SAME-ORIGIN POLICY
SAME-OROGIN POLICY 2
JsonP

Monday, July 2, 2012

Zend Framework Overview

Here's a Great Diagram

OVERVIEW of ZEND FRAMEWORK 1.x


Research each term mentioned in the Diagram to get an even more in-depth look at the CLASSES and INTERFACES that make up the ZEND FRAMEWORK

Source: The Official Zend Framework Site

Monday, June 25, 2012

PHP Unit - Example Unit Test

  1. The tests for a class Class go into a class ClassTest.
  2. ClassTest inherits (most of the time) from PHPUnit_Framework_TestCase.
  3. The tests are public methods that are named test*.
    Alternatively, you can use the @test annotation in a method's docblock to mark it as a test method.
  4. Inside the test methods, assertion methods such as assertEquals() (see the section called “Assertions”) are used to assert that an actual value matches an expected value.

class StackTest extends PHPUnit_Framework_TestCase
{
    public function testPushAndPop()
    {
        $stack = array();
        $this->assertEquals(0, count($stack));
 
        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));
 
        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
}

Here's a List of the ASSERTIONS
Assertions
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertCount()
assertEmpty()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertInstanceOf()
assertInternalType()
assertLessThan()
assertLessThanOrEqual()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMatchesFormat()
assertStringMatchesFormatFile()
assertSame()
assertSelectCount()
assertSelectEquals()
assertSelectRegExp()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertTag()
assertThat()
assertTrue()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()

REST Webservices with PHP in 3 Steps

1. Send Everything to index.php  using .htaccess 


RewriteEngine On    
RewriteBase /     

RewriteCond %{REQUEST_FILENAME} !-f    
RewriteCond %{REQUEST_FILENAME} !-d    
RewriteRule ^(.*)$ index.php/$1 [L] 

2. Figure Out What Was Requested 


class Request
{    
public $url_elements;    
public $verb;    
public $parameters;      
public function __construct()
{        
   $this->verb = $_SERVER['REQUEST_METHOD'];        
   $this->url_elements = explode('/', $_SERVER['PATH_INFO']); 

<continued below in Step 3>

3. Process Incoming Data  according to format

<continued from Step 2> 

   $this->parseIncomingParams();        

// initialise json as default format        
   $this->format = 'json';        

   if(isset($this->parameters['format']))
   {            
     $this->format = $this->parameters['format'];        
    }
        
return true;    
} //end of public function __construct()   

public function parseIncomingParams()

{        
  $parameters = array();          

// first of all, retrieve the GET vars        
  if (isset($_SERVER['QUERY_STRING']))
  {            
     parse_str($_SERVER['QUERY_STRING'], $parameters);        
   }          

// now how about PUT/POST bodies? These override what we got from GET        

  $body = file_get_contents("php://input");        
  $content_type = false;        

  if(isset($_SERVER['CONTENT_TYPE']))
   {            
      $content_type = $_SERVER['CONTENT_TYPE'];        
    }        

  switch($content_type)
   {            
     case "application/json":                
     $body_params = json_decode($body);                

     if($body_params)
      {                    
         foreach($body_params as $param_name => $param_value)
           {                        
              $parameters[$param_name] = $param_value;                    
            }                
       }                
     $this->format = "json";                
     break;            

   case "application/x-www-form-urlencoded":                
   parse_str($body, $postvars);                
   foreach($postvars as $field => $value)
     {                    
        $parameters[$field] = $value;                  
      }                
   $this->format = "html";                
   break;            

   default:               
   // we could parse other supported formats here                
   break;        
  }        //end of switch($content_type)

 $this->parameters = $parameters;
}  // end of public function parseIncomingParams()
} // end of class Request

Friday, June 22, 2012

PHP Architecture - 3 tier & MVC



Great Articles on Architecture here 

http://www.tonymarston.net/php-mysql/sample-application.html

JSON format is not safe for associative arrays

 The PHP Function json_decode() will return associative arrays as objects:
This changes things when you decode your json encoded data object.

Look at the following example I found reading a Nice Post at Stackoverflow

Here's an associative Array

$config = array(
    'Frodo'   => 'hobbit',
    'Gimli'   => 'dwarf',
    'Gandalf' => 'wizard',
    );
Lets act On It

print_r($config);
print_r(json_decode(json_encode($config)));
 
 
The Output is:

Array
(
    [Frodo] => hobbit
    [Gimli] => dwarf
    [Gandalf] => wizard)
stdClass Object
(
    [Frodo] => hobbit
    [Gimli] => dwarf
    [Gandalf] => wizard)

Difference between Abstract class and Interface

PHP 

Abstract Class Interface
Abstract methods doesn’t have any implementation. Any class that contains at least one abstract method must also be abstract Interface methods by default are abstract methods only. So one cannot declare variables or concrete methods in interfaces.
The Abstract methods can declare with Access modifiers like public, internal, protected. ' When implementing in subclass these methods must be defined with the same (or a less restricted) visibility. All methods must be public.
Abstract class can contain variables and concrete methods. Interfaces cannot contain variables and concrete methods except constants.
A class can Inherit only one Abstract class. Multiple inheritance is not possible for Abstract class. A class can implement many interfaces. Multiple interface inheritance is possible.

 


.NET
Feature
Abstract class
Interface
Multiple inheritance A class may inherit only one abstract class. A class may inherit several interfaces.
Can Provide Code Can provide complete, default code just the details that have to be overridden. Cannot provide any code, just the signature.
Access Modfiers Any access modifiers for the methods or properties Public methods only
Homogeneity Use for common behaviour Use only for shared method signatures.
Fields and Constants An abstract class can have fields and constrants defined No fields can be defined in interfaces



PHP Exception Handling

An exception can be thrown, and caught ("catched") within PHP.
 Code may be surrounded in a try block, to facilitate the catching of potential exceptions.
Each try must have at least one corresponding catch block.
Multiple catch blocks can be used to catch different classes of exceptions.
Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present)
will continue after that last catch block defined in sequence.

Exceptions can be thrown (or re-thrown) within a catch block.

When an exception is thrown, code following the statement will not be executed,
and PHP will attempt to find the first matching catch block.
If an exception is not caught, a PHP Fatal Error will be issued
With an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

The following is an example of a re-thrown exception and the using of getPrevious function:

<?php



$name = "Name";



//check if the name contains only letters, and does not contain the word name



try

   {

    try

       {  

          if (preg_match('/[^a-z]/i', $name))

            {

              throw new Exception("$name contains character other than a-z A-Z");

            }  

          if(strpos(strtolower($name), 'name') !== FALSE)

           {

              throw new Exception("$name contains the word name");

           }

       echo "The Name is valid";

     }

     catch(Exception $e)

      {

        throw new Exception("insert name again",0,$e);

      }

   }



catch (Exception $e)

   {

   if ($e->getPrevious())

   {

    echo "The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";

   }

   echo "The Exception is: ".$e->getMessage()."<br/>";

   }

 ?>

Friday, July 1, 2011

APACHE 2 Performance tuning

Apache 2 Webserver Performance Tutorial



mod_gzipIf a clients Request contains Accept-encoding: gzip, deflate in the header then you should allow your webserver to serve your pages compressed.


mod_bandwidth
Mod_bandwidth is a bandwidth throttling module, useful for keeping the traffic of a whole Apache installation or of specific VirtualHosts or directories in check
mod_proxy
Another method to reduce traffic for a specific server and increase the speed with which pages are served is by using a front proxy.


KeepAlive and KeepAliveTimeout
The KeepAlive directive allows multiple requests to be sent over the same TCP connection. This is particularly useful while serving HTML pages with lot of images.

MaxRequestsPerChild
The MaxRequestsPerChild directive sets the limit on the number of requests that an individual child server process will handle.

MinSpareServers, MaxSpareServers, and StartServers
MaxSpareServers and MinSpareServers determine how many child processes to keep while waiting for requests. If the MinSpareServers is too low and a bunch of requests come in, then Apache will have to spawn additional child processes to serve the requests. Creating child processes is relatively expensive.Tune MinSpareServers and MaxSpareServers such that Apache need not frequently spwan more than 4 child processes per second


MaxClients
The MaxClients sets the limit on maximum simultaneous requests that can be supported by the server

AllowOverride
If AllowOverride is not set to 'None', then Apache will attempt to open .htaccess file (as specified by AccessFileName directive) in each directory that it visits.

When using Allow from or Deny from directives, use IP address instead of a domain name or a hostname. Otherwise a double DNS lookup is performed to make sure that the domain name or the hostname is not being spoofed.

Choose appropriate MPM
Apache server ships with a selection of Multi-Processing Modules (MPMs) which are responsible for binding to network ports on the machine, accepting requests, and dispatching children to handle the requests. Only one MPM can be loaded into the server at any time.

DECISION FACTORS
1. whether the OS supports threads
2. how much memory is available
3. scalability versus stability,
4. whether non-thread-safe third-party modules are used, etc..
     Linux systems can choose to use a threaded MPM like worker or a
     non-threaded MPM like prefork.

A.   Worker MPM
  1. uses multiple child processes.
  2. It's multi-threaded within each child and each thread handles a single connection.
  3. Worker is fast and highly scalable and the memory footprint is comparatively low.
  4. It's well suited for multiple processors.

Worker is less tolerant to faulty modules and faulty threads can affect all the threads in a child process.

B. Prefork MPM
uses multiple child processes, each child handles one connection at a time. Prefork is well suited for single or double CPU systems, speed is comparable to that of worker and it's highly tolerant to faulty modules and crashing children. But the memory usage is high, more traffic leads to more memory usage.

Load only the required modules
 This reduces the memory footprint and hence the server performance.