Archive for the ‘PHP’ Category
Coding standard, coding style
In Orange Bus we have been looking at our coding style lately. We have created our very own coding standard. Since we base most of our applications on the drupal we chose to use the drupal coding standard as our main source of inspiration.
During our process of creating this coding standard we found a few good links I thought we should share.
Mike @ Orange Bus found these two articles about beautiful and practical code, both these are a must read:
http://www.wilshipley.com/blog/2007/05/pimp-my-code-part-14-be-inflexible.html
http://www.perforce.com/perforce/papers/prettycode.html
Another blog post about line density worth reading is:
Templating with Eclipse
Today I came over a a post on dzone.com about Eclipse and templating. It turns out that you can write small templates of code snippets you use a lot and bind them to a keyword. When typing the keyword, press “ctrl” and “space” and a list of possible templates available will appear, select the prefered template, press “enter” and the code snippet is inserted into your working code. I works just the same way code completion. This actually means that you do not have to write the boring “for” loops or “if” tests anymore, just write a template and become a more efficient developer.
The original post explains how to set up templates, so I will not go into that in this post, but since I am primarily a PHP developer and the post describes templating for Java, I’ll just give a description of where to go if you use the PHPEclipse.
To edit and create templates for PHP, HTML or css, even javascript you have to use this path:
window -> preferences -> PHPeclipse Web Development -> PHP -> Templates.
To write and edit the templates, just follow the guidelines from Mr. Graversen, or have a look at the links below.
For further reading have a look these sites.
- http://firstclassthoughts.co.uk/java/eclipse_tip_templates_public_static_final.html
- http://www.phpeclipse.de/tiki-index.php?page=Howto+use+the+templates+system
- http://help.eclipse.org/help21/index.jsp?topic=/org.eclipse.jdt.doc.user/concepts/ctemplates.htm
I guess if I had read the PHPEclipse manual when I first started using Eclipse, I would probably been using it from the start
Good luck with your Eclipse templates, I know I will be using them extensively.
The View Helper pattern
Developing MVC (Model View Controller pattern) applications in PHP or any other language often require a lot from the view tier. The view needs to process data received from the model tier and form it into presentable data, it also has to manage user input and form that into data understandable for the model tier.
This might not be a big issue while working with small application, but when it comes to midscale and large applications the view helper pattern can be of great help. The view helper pattern is one of the J2EE core patterns and the documentation can be found on:
http://java.sun.com/blueprints/corej2eepatterns/Patterns/ViewHelper.html
What does the helper pattern do?
First of all the helper pattern adds an extra tier to the system, this tier can be seen as a mid tier which has some understanding of the logic of the system, it knows a little bit about the view and a little bit about the model. Another cool thing is that the view helper pattern makes your code more reusable. When moving complex structures from the view and into a view helper it can with ease be used by other views.
Example:
You are writing a web application where the user writes a review of some product, the application should do auto saving of the user input every 20 second using Ajax functionality. The application should of course also save the user input then the user submits the data. The ajax request and the user submit does almost the same thing but the when the user submits the data the view should also store a rating of the product. This require the ajax request and the user submit to be two different views, or one complex view.
In an ordinary MVC system you would have to implement two views with very much of the similar behavior or one complex view. Using the view helper pattern you extract the storage of the user review in a helper which can be reused by both the ajax request view and the user submit view.
I have written a very simple implementation of the example in PHP. The implementation is not complete at all, but it is meant as a proof of concept that the reusability of code in your application can increase using the view helper pattern.
-
<?php
-
-
class ProductReviewHelper
-
{
-
public function __construct(){}
-
-
/**
-
* save the review
-
**/
-
public function save($user_input)
-
{
-
//validate input
-
$input = $this->validate($user_input);
-
-
//saves the review and return the result of the save
-
return $review_manager->save($input['product_id'], $input['review']);
-
}
-
-
/**
-
* validate the input
-
**/
-
public function validate($user_input)
-
{
-
$filter_args = array('product_id' => FILTER_VALIDATE_INT,
-
'review' => FILTER_SANITIZE_STRING);
-
$input = filter_var_array($user_input, $filter_args);
-
-
//do validation
-
return $input;
-
}
-
}
-
<?php
-
-
//Ajax view
-
$review_helper = new ProductReviewHelper();
-
$result = $review_helper->save($_POST);
-
echo $result;
-
exit();
-
?>
-
<?php
-
-
//User submit view
-
$review_helper = new ProductReviewHelper();
-
$review_result = $review_helper->save($_POST);
-
-
$rating_helper = new ProductRatingHelper();
-
$rating_result = $rating_helper->save($_POST);
-
-
//manage the result from the helpers
-
?>
I am sure that the view helper pattern has helped me to write better and more organized code, which is easily understandable and very reusable.
If you do not use the view helper pattern, and still have solved the problem with reusability of code in the view tier please feel free to leave me a comment describing your solution.
Password encryption using PHP
A recent post on dzone.com linked to a article about “password encryption using PHP” written by Stefan Ashwell on total.php.com. In this article he illustrate a how to save user passwords and authenticating users using the sha1 hashing algorithm.
First of all lets all agree that hashing passwords are basics requirements for a secure web application, but is a simple hashing of the password enough? I do not think so.
Here is the scenario, Someone breaks into your system (not through the web application, but for instance through an ssh connection), they get access to your user database or file where you store user account information. The intruder is now in possession of the password and user name of all your users, but still the passwords are hashed with md5, sha1 or an similar hashing method. If the intruder is determined to get into your system and mess up, he may now try to decrypt the passwords using a dictionary word file and brute force (also known as rainbow tables). This method is quite common and is not advanced at all, all it does is looping through the dictionary file, which contains all words and common password phrases, do a md5 or sha1 hashing of these words and see if it matches up to the hashed password, if it does it has found a match, and the intruder is able to log into the account.
Even though this brute force method might take some time, he will eventually get the passwords and get full access to the users account. There are however methods to complicate this and even make it impossible for the intruder to get the password using brute force method and that is called salting your password.
Example:
-
-
$salt = '2glkpe895';
-
$password = $_POST['password'];
-
-
$encrypted_password = sha1($salt . $password . $salt);
As you can see the salt is an secret string which is only used by your application, it is prepended and appended to the password. You could of course also go the extra mile and split the password in two and add the salt in the middle of the password, but there might not be any point in doing that.
This makes the word not like any word you will find in an dictionary and therefore the brute force method will not find the password.
The point is that if the intruder get a partial access to some of your system, for instance the user database, it will not be enough to get access to the total system because the security system is layered, one layer in your code, and one layer in your user database.
I do not say that this method is a 100 percent secure but it is is way more secure than not using a salted password.
PHP Vikinger
I attended the PHP vikinger unconference in Skien on Saturday. Rather than writing my own wrap up of the unconference I choose to link to the wrap up written by Mats Lindh and Derick Rethans
Notes from Mats: http://e-mats.org/2008/06/php-vikinger-notes/
Notes from Derick: http://phpvikinger.org/news/news-2008-05-23
Writing SOA applications with PHP
Lately I’ve been working a lot with data integration between several web applications, and a natural choice for the integration was to use a Service Oriented Architecture (SOA). I’ve built both SOA servers and clients before using the SOAP approach, which is a superb way of transferring data when not knowing who the user of the service is, or when you are a client of such a service. However in this setting I knew who the user was, I knew what the service would be used for, also had the chance to write both the client and server.
The choice fell on a simple implementation using the JSON (JavaScript Object Notation) data structure. This is really easy using the built in json library in php. The server use the json_encode() function and the implemented sub class of the client use the json_decode() function.
To simplify this further I implemented two abstract classes, a ServiceServer class and a ServiceClient class. The service server class contained a very simple displayJSONResult function, which sets the correct header, encode the data as json data and echo the data.
The service client class has two main functions, doGetRequest and doPostRequest, both functions use the cURL library in PHP.
Server
-
<?php
-
-
abstract class ServiceServer
-
{
-
-
public function __construct(){}
-
-
protected function displayJSONResult($data)
-
{
-
header('Content-type: text/plain');
-
-
echo json_encode($data);
-
-
exit();
-
}
-
}
Client
-
<?php
-
-
/**
-
* ServiceClient
-
*
-
*
-
* @author Kristian Lunde
-
*
-
*/
-
-
class ServiceClient
-
{
-
-
public function __construct(){}
-
-
/**
-
* do a post request to a service
-
*
-
* the params parameter must be a string with the format:
-
* key=val&key2=val2&key3=val3
-
*
-
* @param string $url
-
* @param string $params
-
*/
-
protected function doPostRequest($url, $params)
-
{
-
$ch = curl_init($url);
-
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
-
curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
-
curl_setopt($ch, CURLOPT_POST , 1);
-
curl_setopt($ch, CURLOPT_POSTFIELDS , $params);
-
$result = curl_exec($ch);
-
curl_close($ch);
-
return $result;
-
}
-
-
/**
-
* do a get request to a service
-
*
-
* @param string $url
-
*
-
* @return mixed
-
*/
-
protected function doGetRequest($url)
-
{
-
$ch = curl_init($url);
-
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
-
curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
-
$result = curl_exec($ch);
-
curl_close($ch);
-
return $result;
-
}
-
-
}
Example
To illustrate the easiness and simplicity of this SOA approach I written a small example. In this example the server finds the country of a city using POST parameters or it can find cities using the country as a GET parameter.
Example server
-
<?php
-
-
/**
-
* Example of using the ServiceServer class
-
*
-
* Returns countries or cities
-
*
-
* @author Kristian Lunde
-
*/
-
-
require_once('ServiceServer.php');
-
-
class ExampleServer extends ServiceServer
-
{
-
-
-
-
public function __construct()
-
{
-
$this->countries = array('norway' => array('Oslo',
-
'Trondheim',
-
'Bergen',
-
'Halden',
-
'Sarpsborg',
-
'Hammerfest'),
-
'sweden' => array('Stockholm',
-
'Gothenburg',
-
'Karlstad'),
-
'england' => array('London',
-
'Newcastle',
-
'Bath',
-
'Liverpool'));
-
-
-
if(isset($_GET['country']))
-
{
-
$this->findCitiesByCountry(trim($_GET['country']));
-
}
-
-
if(isset($_POST['city']))
-
{
-
$this->findCountryByCity(trim($_GET['city']));
-
}
-
}
-
-
public function findCitiesByCountry($country)
-
{
-
$cities = 'Not found';
-
$country = strtolower($country);
-
-
if(isset($this->countries[$country]))
-
{
-
$cities = $this->countries[$country];
-
}
-
-
$this->displayJSONResult($cities);
-
}
-
-
public function findCountryByCity($city)
-
{
-
$country = 'Not found';
-
-
$break = false;
-
foreach($this->countries as $key => $val)
-
{
-
for($i = 0, $count = count($val); $i < $count; $i++)
-
{
-
if($city == $val[$i])
-
{
-
$country = $key;
-
$break = true;
-
break;
-
}
-
}
-
-
if($break)
-
{
-
break;
-
}
-
}
-
-
$this->displayJSONResult($country);
-
}
-
}
-
-
$obj = new ExampleServer();
-
?>
Example client
-
<?php
-
/**
-
* Example of using the ServiceClient class
-
*
-
* does a request to the ExampleServer
-
*
-
* @author Kristian Lunde
-
*/
-
-
require_once('ServiceClient.php');
-
-
class ExampleClient extends ServiceClient
-
{
-
public function __construct()
-
{
-
$this->getCities('Norway');
-
$this->getCounty('Bath');
-
}
-
-
public function getCities($country)
-
{
-
$url = 'http://files.klunde.net/files.klunde.net/ExampleServer.php?country=' . $country;
-
echo $this->doGetRequest($url);
-
}
-
-
public function getCountry($city)
-
{
-
$url = 'http://files.klunde.net/files.klunde.net/ExampleServer.php';
-
$params = 'city=' . $city;
-
-
echo $this->doPostRequest($url, $params);
-
}
-
}
-
$obj = new ExampleClient();
-
?>
I’m quite satisfied with this implementation because it is so easy to maintain and even more important, implementing new services and clients for the services is straight forward and supports rapid development.
Download
Writing exceptions in PHP
Fredrik Johan Holmström has a entry on his blog about writing exceptions in PHP. He points out that several of the large PHP framework assumes that an exception is a fatal error, and that this may be a flaw in the design.
An Exception is not necessarily a fatal error and it should be the responsibility of the code that catches the exception to determine if it is a fatal error or not.
The blog entry got me thinking, and yes I’ve done that mistake a few times myself, I’ll do it right the next time I write an exception in PHP,
URL: http://loveandtheft.org/2008/05/23/exceptions-youre-doing-it-wrong/
Cheat sheets
When talking about cheat sheets, www.ilovejackdaniels.com has a list of a few good cheat sheets. I’ve actually printed some of them at work and taped them to the wall next to my computer.
Thanks to Dave Child for doing the work of putting together these sheets.
PHP vikinger
I just registered for this years PHP vikinger unconference. I’m really looking forward to it ![]()