Archive | Php RSS feed for this section

PHP: Taking care of security

28 Jun

Today highly confidential data such as credit card number, social security number etc are stored and handle through web. So it must be your primary goal to make your web application secure enough, so that users/visitor feels confident enough while using your application.

Here in this article I am going to give you some tips that are worthy to be remembered and taken care of in application development process.

  1. You may have heard about register_globals. They make PHP variables usage easy. However they have certain disadvantages such as users can easily sneak into your application by easily passing data through $_POST, $_GET or $_COOKIE etc. So you shouldn’t rely on register_global. Disable them would be nice decision.
  2. Most of the time we use variable directly, without first initializing them. For example

if (condition) {

$flag = TRUE;

}

If you don’t initialize $flag to false, user can easily set it to true using, $_POST, $_GET or $_COOKIE.

  1. Verify all incoming data before processing. Verification highly depends on the type of data. If you need to insert integer data in the database, make sure that proper data is submitted through form.
  2. Be very much careful when using function that run commands on the server. These function include exec(), passthru() and backticks (“) etc.
  3. You must change the directory where session data is stored by default. Another good approach would be to use database to store session information.
  4. When uploading file to the server, it would be good practice to rename the file(s) before storing them. Name must be safe and not guessable.
  5. Don’t reveal error on live site. Errors reveal very important information, so they must be taken care of.
  6. Take care of SQL injection. If user provides malicious information, your SQL query shouldn’t break.

PHP: using __autoload() for automatically loading php files

30 May

Object oriented programming give great strength to PHP. Now if you need to work on large web application, it’ll be nice to identify entities and construct separate class for each.

Mostly the entities identified in the analysis phase need a separate database tables. So it would be better to define a separate class for each of your database table. The class created encapsulates attributes and methods.

Give it a try, and honestly you will feel lot of strength of object oriented programming.

For example, we have a database table named users, having id, username, email and address.

You can define your table for this table as

<?php

class Users

{

private $_id;

private $_username;

private $_email;

public function __construct()

{

// code for connecting to the database

}

public save($data)

{

// code for saving user data.

}

}

Well, this isn’t a perfect definition of the class, however you can get an idea from this and construct your own according to your needs/requirements.

Large web application often need lots of require/require_once statements.

If you define a separate class for each of you business entity and need multiple classes in a single page, you will need to write as many require statements as the classes you need.

If your application page needs five php files, you will need to write five require statements.

The people behind PHP has given a very simple solution to get rid of this. You need to define a simple __autoload() method in the page, which will load all the class you need using a single require statement.

Let have a simple example.

We have two separate class for person and car.

The person class is define as

<?php

class Person

{

private $_name;

public function setName($n)

{

$this->_name = $n;

}

public function getName()

{

return $this->_name;

}

}

And class Car is defined as

<?

class Car

{

private $_made;

public function setMade($m)

{

$this->_made = $m;

}

public function getMade()

{

return $this->_made;

}

}

Now if you need both these classes in the same file, you can either user two require statements as

require_once(‘person.php’);

require_once(‘car.php’);

And then create objects of each of these classes and call appropriate methods.

$person = new Person();

$car = new Car();

$person->setName(‘faheem’);

$car->setModel();

Although its simple to have two require statements, however if you need more, it becomes painful.

If you remove these two require statements, you will face “Class not found” fetal error.

Using __autoload() method you can get rid of these or as many requirement statements as you require.

Define the following function in the file where you create objects of different classes as

function __autoload($class) {

require_once($class.’.php’);

}

let we have a file named index.php where we need these classes. So our index.php will look like this.

<?

function __autoload($class)

{

require_once($class.’.php’);

}

$person = new Person();

$car = new Car();

$person->setName(‘faheem’);

$car->setModel();

?>

No matter, where you define this method, at the beginning or at the end, result will be the same.

Give it a try and let me know if you face any problem.

PHP: Using DateTime Class to take the pain out of working with dates

28 May

Well, since few days I’m writing about object oriented programming. Object orientation has many advantages over structural programming. It not only lessen your burden by allow you to achieve your desired results with less code, but also enable you to reuse your code in as much places as you wish in your application.

Implementation Object orientation give lot of strength to PHP. Many people may still stick to conventional programming, but all will one day stop writing code in old style structural programming and adopt object oriented programming instead.

I am not going to discuss the benefits of object oriented programming and down sides of conventional, but instead share some knowledge about DateTime class available in the latest version of php.

If you have some knowledge of php and have developed any application, you’ll certainly come across a requirement demanding usage of date or time.

In conventional programming displaying date need to write the following.

echo ‘Current date is ‘ date(‘m-d-y’);

It displays the following.

Current date is 05-28-09

While using the DateTime class, you will need to write the following.

$date = new DateTime();

echo $date->format(‘l, F jS, Y’);

This gives the following result.

Thursday, May 28th, 2009

Well, you may feel that the conventional method is more easy to use, as it only require one line of code.

The Usage of the DateTime class comes handy when you wish to perform some complex tasks.

For example, if you like to display the next Thursday, you will need to writ the following code.

$date = new DateTime(‘next Thursday’);

echo $date->format(‘l, F jS, Y’);

The result of the about would be.

Thursday, June 4th, 2009

As today is Thursday, May 28th, 2009

Only passing “next Thursday” to the constructor, it display the next Thursday for us.

This is one simple usage of the DateTime class. Lets look at some other useful methods of this class.

To have the current date, write

$date = new DateTime();

If you want to set specified date, you can do it either by passing string argument to its constructor as

$date = new DateTime(“18-July-2008 16:30:30”);

And then display as

echo $date->format(‘l, F jS, Y’);

Or call empty constructor and then use setDate method as

$date = new DateTime();

$date->set(“year”,”month”,”day”);

For example

$date->setDate(“2008″,”05″,”18”);

Similarly you can set time as

$date->setTime(int $hour, int $minutes [, int $seconds]);

For example

$date->setTime(“16”,”30”,”30”);

Another useful method is modify for modification of the date time.

If you want to add a day to the current date, write

$date = new DateTime();

$date->modify(“+1 day”);

This add a single day to the current date and display the next day.

Similarly if you want to subtract a day, write

$date->modify(“-1 day”);

Also you can add and subtract month and years as

$date->modify(“+1 month”);

$date->modify(“+1 year”);

And

$date->modify(”-1 month”);

$date->modify(“-1 year”);

If you want to get the time zone, writ an single line

$date->getTimeZone()->getName();

And similarly setting time zone can be done like this.

$date->setTimeZone(new DateTimeZone(“Asia/Karachi”));

PHP: Method chaining using object oriented programming

27 May

While in my previous article I discussed some of the nice thing of object oriented programming. Inheritance –creating sub classes from inheriting parent, contain all the attributes of the parent class plus its own. Polymorphism, means different form, like overloading and overriding methods and dynamic binding- deciding which class in the inheritance tree should be called on runtime, are techniques that give great benefits to programmers.

In this article I am going to show you a simple but very useful trick while using “this” keyword for method chaining. “this” when use in the class refer to the same class.

Consider the following example.

class Person {

protected $_name;

protected $_age;

protected $_gender;

public function setName($name) {

$this->_name  = $name;

}

public function getName() {

return $this->_name;

}

public function setAge ($age) {

$this->_name  = $age;

}

public function getAge() {

return $this->_age;

}

public function setGender($gender) {

$this->_gender  = $gender;

}

public function getGender() {

return $this->_gender;

}

}

While in object oriented programming it’s always a good practice to define getter and setters.

To create an object of the above class and define person properties, we will need to write the following code.

$person = new Person();

$person->setName(“person_name”);

$person->setAge(24);

$person->setGender(“male”);

And now If you want to get these values, write

$person->getName();

$person->getAge();

$person->getGender();

Well, if you want to set values using a single statement, you will need a code similar to this.

$this->setName(‘person_name’)->setAge(24)->setGender(“male”);

To achieve this, you will need to write the following statement in all your setters.

public function setName($name) {

$this->_name  = $name;

return $this;

}

The only thing we need here is “return $this”. This statement return a reference to the same object.

Place this statement in your setAge() and setGender(), and now you can write

$this->setName(‘person_name’)->setAge(24)->setGender(“male”);

for setting all the three properties

PHP: Object Oriented Programming

26 May

Object oriented programming concepts were introduced in PHP version 1.4, I guess.

How many people around you play with object oriented programming?

If not working in any kind of MVC frameworks, I guess very short number of people.

Developers are often used to structured programming and don’t bother themselves learning object oriented programming concepts and paradigm.

Well, when software engineers realized that it’d become very difficult to manage and maintain thousand lines of code, object oriented programming was introduced. Since then dramatic improvements have been done to OOP.

In object oriented programming inheritance, polymorphism, encapsulation, dynamic binding and exception handling has great usage and advantage, however class and objects are the most basic concept.

Class is blue print containing properties and method associated with same entity. Object is the instance of the class and is used to access properties and method of the class.

In addition to OOP, design pattern make jobs easier for the programmers.

Singleton, factory and specially MVC design patterns are very useful these days.

In singleton design pattern one object of the class exist throughout the life cycle of the software application. If programmer tries to instantiate another object of the same class, a reference to the object instantiated earlier, is granted.

A class implementing factory design pattern works as bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as backend, but in future need to change backend database to oracle. Without using factory design pattern, you will need to modify all your code.

In factory design pattern you need to do very little work to achieve this. A class implementing factory design pattern takes care for you and lessen your burden.

In MVC design pattern M stands for Model. Model contains your application’s business logic.

V stands for View. It’s the presentation layer.

While C stands for controller that work as glue between view and model.

PHP: Creating JSON response, a real world example

4 May

While working with AJAX, you will need to get data after sending request to the server. You can use three ways to get the data form the server.

  1. In xml Format
  2. HTML Format
  3. Json Format

Though xml has several advantages, however processing data at the client will put extra burden.

HTML, can easily be handle, is however more resource or you can say bandwidth extensive.

So JSON fall in the middle of both.

PHP provide a very easy way to create JSON response. Once you get data at client side you will need much later code to process response than xml document.

Let’s first look at the server side.

For example we have the following array.

$data = array(‘items’=>array(‘firstname’=>’faheem’, ‘lastname’=>’abbas’,’address’=>’pakistan’));

To create JSON response, simply write

echo json_encode($data);

This will give the following result

{“items”:{“firstname”:”faheem”,”lastname”:”abbas”,”address”:”pakistan”}}

Now at the client side to send AJAX request, you will need to create the following code.

Keep in mind that we are using prototype for making AJAX request.

<script>

function getData()

{

new Ajax.Request(

“http://localhost/getdata.php”, /* this is url of the php file that create JSON response.*/

{

method:’post’,

onSuccess: processData

}

);

}

function processData(rsp)

{

var response = eval(‘(‘ + rsp.responseText + ‘)’);

var firstname = response.items(0).firstname;

var lastname = response.items(0).lastname;

var address  = response.items(0).address;

}

</script>

PHP: Listing files in particular directory, a real world example

6 Mar

We are preparing our static files specially java script, css and images files to be moved to Amazon CDN. The thing we need to make sure here is that only those files that are in use should be moved. I was given a task to list all the js, css and images we are currently using in our application.

Initially I opened notepad and start writing down the names of those files.

Hehe, we don’t think out of the box.

The whole process was disgusting and I was feeling tired.

However working for a bit of time, an idea come to my mind, why not use computer to do the task for me.

And this is what I did.

Create .php file and write the following code in that file.

<form action=”” method=”post”>

<input type=”text” name=”path” />

<br>

<input type=”submit” value=”Submit” />

</form>

<?php

$pathName = $_POST[‘path’];

if($pathName){

$dir = new DirectoryIterator($pathName);

foreach($dir as $fileInfo) {

if($fileInfo->isDot()) {

// do nothing

} else {

echo $fileInfo->__toString().'<br>’;

}

}

}

?>

The code above did everything for me. Created a list of files in particular directory. I took print out of that list and crossed (x) files under construction.

In the first few lines I am creating form, adding input box for the directory path to be entered and submit button.

In the php code

  1. I get the path
  2. If path is not empty, I create an instance of DirectoryIterator available in PHP5, giving it directory path entered via input box.

3.Loop the $dir object and echo the result as string.