Posted by: Shofiur Rahman

Posted on: July 25, 2012 3:14 pm

-

PHP5 has provided magic methods to make Object Oriented Programming (OOP) easier. These magic methods are specially named methods for all classes, which are called automatically in certain scenarios.

Some Magic methods in PHP5

__construct() Called when an object is instantiated.
__destruct() Called when an object is destroyed.
__call() Provide actions or return values when undefined methods are called on an object.
__get () To specify custom functions to store and retrieve data in properties that are not already defined in the class. It takes one argument, the name of the property.
__set() Same as __get() method but it requires 2 arguments: the name of the property and the new value.
__toString() Returns a custom string value that is automatically used when the object is converted to a string.

Posted by: Shofiur Rahman

Posted on: July 11, 2012 4:13 pm

-

Every day hackers are discovering new exploits and hacking techniques. We can defend some categories of attacks in our PHP script.

Abusing register_globals

It is a setting in php.ini that controls the auto population of variables with the same name as form elements or cookies. If register_globals set to on then it may bring a disaster for your website.

Since PHP 4.2.0, the default value for register_globals is off. But often web hosts will re-enable register_globals to provide compatibility with older scripts. We can get clear concept of register_globals on or off with the following example.

Suppose username is a form element. With register_globals ‘off’, the only way to get the value of this form element using $_POST or $_GET array, depending on form action method. On the other hand, when register_globals is ‘on’, the username field value is accessible using $_POST, $_GET and $username as well.

If you are not able to disable register_globals in php.ini, you can turn it off use an .htaccess file.

php_flag register_globals off

SQL Injection Attacks

SQL injection attacks are simply the inclusion of malicious SQL statements in the place of what should normally be inoffensive data. SQL injection preys on a lack of input scrubbing and data validation.

SQL injection is fairly avoidable with an insignificant preparation and thorough coding practices. If magic_quotes_gpc is enabled, PHP automatically escapes any escape characters (e.g. apostrophes). Unluckily, this activities is applied to all GET, POST and Cookie variables in spite of whether they are going to used in a SQL statement or not. Most of the time it can be annoying. To make sure the data is escaped only when we need it to be, we can turn off magic_quotes_gpc in php.ini, and use addslashes() on all data that is being passed to MySQL. The addslashes() function will automatically escape any unsafe characters so our input will not choke MySQL.

Cross-Site Scripting

Cross-Site Scripting abbreviated XSS, cross-site scripting is the abuse of unfiltered dynamic output, where the invader has the skill to add or change the page’s generated markup. Most commonly, this means the addition of a small bit of JavaScript to the output of a page, which then does something ominous, such as trick another user into revealing their login credentials or credit card information, or possibly divulging cookie or session information for immediate account compromise.

Posted by: Shofiur Rahman

Posted on: July 4, 2012 3:46 pm

-

The basic four steps to generate an image using PHP are as follows:

  • Creating a canvas image on which to work.
  • Drawing Shapes or printing text on that canvas.
  • Outputting the final graphic
  • Cleaning up resources.

Sample PHP script:

// Creating a canvas image

$height = 200;

$width = 200;

$im = imagecreate($width, $height);

$white = imagecolorallocate($im, 255, 255, 255);

$black = imagecolorallocate($im, 0, 0, 0);

// Drawing Shapes or printing text

imagefill($im, 0, 0, $black);

imageline($im, 0, 0, $width, $height, $white);

imagestring($im, 4, 50, 150, 'Label text', $white);

// Output image

header('Content-type: image/png');

imagepng($im);

// Clean up

imagedestroy($im);

?>

Posted by: Shofiur Rahman

Posted on: June 27, 2012 4:32 pm

-

To authenticate a user includes the following steps:

  • Identifying visitors
  • Implementing access control
  • Authentication

Identifying Visitors

The web is fairly anonymous medium, but it is often useful to know who is visiting your site to focus on right business area. You are able to get little about the visitors due to users privacy. With a little work server can find out quite lot about users computers, networks, browsers, etc.  From visitor’s IP address you are able to know visitor’s geographic location.

Implementing access control

Simple access control is not difficult to implement. A simple PHP script is shown below.

<?php
//create short names for variables

$name = $HTTP_POST_VARS['name'];

$password = $HTTP_POST_VARS['password'];

if(empty($name) || empty($password)){

//Visitor needs to enter a name and passwor.

?>

<strong>Please Log In</strong>

<form method=”post” action=”login.php”>
<label>User Name: </label> <input type=”text” name=”name” />
<label>Password:</label> <input type=”password” name=”password” />
<input type=”submit” value=”Log In” />

</form>

<?php

}

else if($name==’user’&& $password==’pass’){

//login successful

}

else {
//login failed
}

?>

Encrypting passwords

To secure the access control you need to implement encryption algorithm on the user login. The PHP function crypt () provides a one-way cryptographic hash function. The prototype for this function is

String crypt (string str [, string salt])

Basic Authentication in PHP

There are some built-in authentication facilities in to HTTP. Scripts or web servers can request authentication from a web browser. The web browser is then responsible for displaying a dialog box or similar device to get required information from the user.

PHP scripts are generally cross-platform, but using basic authentication relies on environment variables set by the server.  A sample of HTTP basic authentication using PHP is shown below.

<?php
// if we are using IIS, we need to set $PHP_AUTH_USER and $PHP_AUTH_PW

if(substr($SERVER_SOFTWARE, 0, 9) == ‘Microsoft’ && !isset($PHP_AUTH_USER) && !isset($PHP_AUTH_PW) && substr($HTTP_AUTHORIZATION, 0, 6) == ‘Basic’)
{

list($PHP_AUTH_USER, $PHP_AUTH_PW) = explode(‘:’, base64_decode(substr($HTTP_AUTHORIZATION, 6)));

}

//Replace this if statement with a database query or similar

if($PHP_AUTH_USER!=’user’ || $PHP_AUTH_PW != ‘pass’)

{

// Visitor has not yet given details, or their
// name and password combination are not correct

header(‘WWW-Authenticate: Basic realm=”Realm-Name”‘);
if(substr($SERVER_SOFTWARE, 0, 9) == ‘Microsoft’)
header(‘Status: 401 Unauthorized’);

else
header(‘HTTP/1.0 401 Unauthorized’);

echo ‘You are not authorized to view this resource.’;

}

else {

// visitor provided correct details.

}

?>

Posted by: SEO Positive

Posted on: February 2, 2011 10:56 am

-

One bug I fixed this week was down to one of the features of file_exists() function. File_exists(string $filename ) will return true if the filename points to a file or directory. Is_file( string $filename ) will return false if the given path is a directory. To check whether filename is actually a file, use is_file().

For both, $filename cannot be a relative path, so I always use document root to ensure an absolute path.


if( file_exists( $_SERVER{'DOCUMENT_ROOT'} . "/images/picture.jpg")) {
...
}
?>

Posted by: SEO Positive

Posted on: November 29, 2010 11:55 am

-

All developers have to transfer sites at some point, if you don’t I envy you. It seems that site transfers always have teething issues with the difference in server builds, operating systems having different compilations of PHP and the rest.

And worst of all, different hosts limitations…

But to transfer a site you need to make a simple list of things that need to be done in order for it to work.

  • Get all files, including hidden files (many a time I’ve been caught up on the .htaccess on a mac being hidden and a site riddled with 404 errors…)
  • Get all database details of the new server
  • Update all calls to databases
  • Use Dream Weaver (for the only things its any good for) to search and replace across the site for the old URL and change it to the new one, and the same with database details)
  • Make sure image, stylesheet, javascript and any other call is base root not an absolute URL (unless externally hosted)
  • Upload everything, including creating the new databases
  • Test everything, fix bugs and teething issues

If you can do all of the above your site will transfer easy peasy.

Posted by: SEO Positive

Posted on: November 24, 2010 1:22 pm

-

Every developer knows just how many if and else statements are needed for validation, data checks, state checks, etc.

And they take up a lot of space and cause necessary amounts of code, this tutorial is about to teach you a way to make your if and else statements all on one single line.

Ternary Operator

The ternary operator is an if else statement compressed to one single line using the ? and : operands, see below for an example ternary operator

$apples = ( $colour == 'green' ) ? 'Tasty green apples' : 'Nasty rotten apples' ;

The above is the exact equivalent to the below:

if( $color == 'green' ) {
       $apples = 'Tasty green apples';
}
else {
      $apples = 'Nasty rotten apples';
}

Which we can all agree is far more troublesome and big, some people say that an if and else statement is easier to read than a ternary operator. It can be argued until man steps foot on Mars its a personal preference thing. Personally, I use the ternary operator wherever possible but sometimes its not possible. See below for an example that you couldn’t use a ternary operator for:

if ( $database->row_result == 'something' ) {
       $database->row_result = substr ( $database->row_result, 0, 100 );
       $this->some_cool_function( $database->row_result );
       return validate_the_above ( );
}
else {
       throw new RunTimeException ( 'the result was in a malformed state' );
       exit;
}

The reason the above will not work in a ternary operator is the required state involves multiple lines of code in order to finish the operation (whatever yours is) and a ternary operator will only handle function calls, variable setting and validation.

In essence the ternary operator is a great getter and setter method (until PHP6 is released with C style getters and setters).

But what if you only wanted to validate something was there and use the else?

Since PHP 5.3 they have made this shortcut available see below for an example.

$apples = ( $colour == 'brown' ) ?: 'Nasty rotten apples';

Notice the above has no true statement and will only set in the event of a false validation.

Posted by: SEO Positive

Posted on: November 22, 2010 9:18 am

-

Anyone asking for the ability to pull data off another website or to globalise a collection of links or anything you want will come across the file_get_contents function. This function is very useful for data scraping or for generalising a collection of links or general content.

The function itself does nothing but puts the source of the web page you supply it into a string available for use throughout your script.

It does have sister functions such as file() which puts the source code into an indexed array (a new array element for every line of code) and CURL.

While there are a huge number of solutions to doing this, file_get_contents is for me the easiest as with regular expressions its unstoppable.

To use file_get_contents():

$data = @file_get_contents( "http://www.bbc.co.uk/" );
if( $data ) echo htmlentities( $data );

The above will output the source code of the very latest BBC home page (with html entities so you get the source not just a reconstructed bbc home page)

Using regular expressions you can pull any piece of data throughout the source code.

Posted by: SEO Positive

Posted on: November 3, 2010 9:12 am

-

Method chaining is becoming an increasingly popular technique in the programmers world, but not a lot of people understand it.

This short tutorial will hopefully shed light on:

  1. what it is
  2. what it does

So what is method chaining?

To answer this question I have to show you some basic classes, see below for a standard class and method set.

class random_functions{
     function format($string, $f = 'uppercase'){
            switch($f){
                 case 'uppercase':
                       $string = strtoupper($string);
                 break;
                 case 'lowercase':
                       $string = strtolower($string);
                 break;
             }
             return $string;
     }
     function strings($string, $filter = 'trim'){
            switch($filter){
                  case 'trim':
                         $string = trim($string);
                  break;
                  case 'mres':
                         $string = mysql_real_escape_string($string);
                  break;
             }
             return $string;
      }
}

To use the above class, instantiation is the usual

$functions = new random_functions();
echo $functions->strings($functions->format($string, 'lowercase'), 'mres');

Which, to me at least, looks awful, its hard to read and just generally not very easy to work with.
What method chaining allows us to do is keep our functions separate and make our re-usable code a lot easier to read and understand as this requires a lot of logical thought in to how you want it to work and even makes planning easier due to having to put your functions in the correct order to achieve what you want.

See below for the same class that allows method chaining.

class random_functions{

     static $output = '';

     function format($string, $f = 'uppercase'){
            switch($f){
                 case 'uppercase':
                       self::$output = strtoupper($string);
                 break;
                 case 'lowercase':
                       self::$output = strtolower($string);
                 break;
             }
             return $this;
     }
     function strings($string = '', $filter = 'trim'){
            switch($filter){
                  case 'trim':
                         self::$output = $string ? trim($string) : trim(self::$output);
                  break;
                  case 'mres':
                         self::$output = $string ? mysql_real_escape_string($string) : mysql_real_escape_string(self::$output);
                  break;
             }
             return $this;
      }
      function output($in = ''){
             echo $in ? $in : self::$output;
             return $this;
      }
}

And the use of this is much clearer and much easier, see below for the use and an explanation of the code.

$functions = new random_functions();
$functions->format('Foo Bar', 'lowercase')->strings()->output();

As you can see, there are arrows between each function call, this is called method chaining. This helps us keep our code clean, semantic and easy to read and understand.

Lets analyze the code

In order to make things easier I added a class variable to work from, this variable is available to every function within the class and I use it to validate input to functions and give us something to work from and around if needed. I also changed each return.

Instead of returning our formatted string, I’ve changed each return to $this what $this means is “the current object” which in a class means the class object.

The class object?

Classes are objects, with children (the methods/functions within the class) and to make any function chainable within a class all you have to do is return an object. You cannot make static methods chainable i.e

class random_functions{

     static $output = '';

     static function format($string, $f = 'uppercase'){
            switch($f){
                 case 'uppercase':
                       self::$output = strtoupper($string);
                 break;
                 case 'lowercase':
                       self::$output = strtolower($string);
                 break;
             }
             return $this;
     }
    static function strings($string = '', $filter = 'trim'){
            switch($filter){
                  case 'trim':
                         self::$output = $string ? trim($string) : trim(self::$output);
                  break;
                  case 'mres':
                         self::$output = $string ? mysql_real_escape_string($string) : mysql_real_escape_string(self::$output);
                  break;
             }
             return $this;
      }
     static function output($in = ''){
             echo $in ? $in : self::$output;
             return $this;
      }
}

random_functions::format('Foo Bar', 'lowercase')::strings()::output();

Will not work, this will return a fatal error.

But to make a static method chainable you must return a new object as $this is undefined in a static method as the parent becomes self

We hope that you enjoyed this tutorial and its helped you understand the ideology of method chaining and how it is useful.

Posted by: SEO Positive

Posted on: October 6, 2010 8:16 am

-

Continuing on from a previous post about page speed, anything built in PHP beyond something simple should be class based to prevent duplication of code and keep your web pages  as small as possible.

But what are PHP Classes?

Well PHP Classes ventures into the OOP area (That’s Object Orientated Programming) and a class is a collection of functions, variables and general behavior depending on your class structure.

This is an example of a PHP class.

//mordor.php
class my_precious
{
         public static function mordor($ring = null)
         {
                   if($ring !== 'ring') return "Well... Where's the ring? I don't want your {$ring}";
                   else return 'Well... That\'s all evil taken care of... Gratz';
         }
}

So as you can see, its fairly simple to do. Really its just keeping your code in one collated name space, without the above code being in a class the most efficient way to deal with that would be to build a whole line of if and else statements to capture any data on any page you wanted to display your Mordor paddy.

Of course when you’re building massive projects classes may seem a lot more efficient but the above code was a syntax example. To use the above code, all you need on any page is the below code.

require 'mordor.php';
echo my_precious::mordor('Cheese and ham Toastie');

Which we’ll all agree is a lot less hassle than writing a script and copy and pasting it all over every page you want the validation/script to run on. Having to only put 2 lines of code into a page will keep your page sizes down and involves a lot less on page server action with if and else statements littered everywhere to catch and modify data in and out of the page.

While procedural code may have some advantages for building a website with PHP, unless its a single query and including an entire class and its children is entirely arbitrary PHP Classes are the way to go forwards.

Happy coding!

Authors
Categories
Archives
Blogroll