Author Archives: Rob Allport

About Rob Allport

Web Developer based in Stoke-on-Trent Staffordshire Google+ - Twitter

Passing Arguments as an Associative Array to a Function

Sometimes is it useful and slightly cleaner to pass arguements to a function via an associative array as opposed to a list of variables. There are a variety of methods to achieve this, such as using PHP’s extract function – but the below is cleaner in my opinion. Please note, the following functionality is common place when using a good MVC framework, or a good CodeIgniter base class. Take a sample PHP class:

class setOptions {

    var $temp = '/default_temp/';
    var $upload = '/default_upload/';
    var $cache_time = '0';
    var $cache_status = '0';
    var $cache_file = 'users.txt';

    function __construct($user_settings)
        if (is_array($user_settings)) {
            foreach($user_settings as $k=>$v)  {
                $this->assignSetting($k, $v);
        } else {
            die('Config Error!');

    function assignSetting($name, $value)
        $whitelist = array('temp', 'upload', 'cache_time', 'cache_status', 'cache_file');

        if (in_array($name, $whitelist)) {
            $property = $name;
            $this->$property = $value;


In lines 3 – 6 we set the default values of our settings that are used an our class. We can choose to leave these as they are, or pass the class an array of new setting, to overwrite them.

In line 8 the settings array, as an associative array, is passed to the magic construct function so all the settings are available when the class is called. On line 10, we check to ensure that the data passed to the function is actually an array and on line 11 we simply through each key/value of the array.

On each iteration, the assignSetting function is called (line 17). The function takes a setting name and value as it’s arguements. On line 19 a whitelist of allowed settings is created as an array. Line 20 checks to ensure the setting we are attempting to add is within this whitelist.

Continue reading

The Importance of Client Requirement Analysis

Recently I developed a small bespoke CRM system for a client, based on list of requirements gathered by a colleague approximately 2 months ago. The CRM was nothing out of the oridinary – a maintable customer database, customer login system, email marketing functionality, customer account reminders, invoice associatiion with specific customers etc.

Overall, did the customer get what they? Yes. Did the project take a lot longer than it should have? Definately! The reason for the latter – poor initial requirements analysis from my colleague.

Continue reading

PHP Email Template with Flat Files

It’s quite common when sending an email message to see the following code to set the message body:

$body = "Hi $firstname $lastname,<br /><br />
	Thank you for you recent order - reference <strong>$order_id</strong><br /><br />
	A secure payment for your order of <strong>&pound;$order_value</strong> was successfully processed.<br /><br />
	The estimated delivery date is <strong>$order_date</strong>.<br /><br />
	The Admin";

This is quite messy and mixes html and php, which isn’t ideal – ideally, we’d want a php email template for use across our whole site. Additionally, this code is time consuming to update as you need to manually go back to the raw PHP code if you needed to change the email.

A very simple solution is to use a flat file (.txt file for example, although could be a html or .tpl file) to store the basic email content with placeholders to replace various bits of information that change. For example, part of a template may contain:

Hi {firstname} {lastname},

All the information srrounded by the curley brackets (I’m sure they have a proper name) are the parts of the email that will change. All we need to are pass information to each of these using our very very simple email templating system:

Firstly include the path to your template file. If the file doesn’t exist, stop the script immediately:

Continue reading

Associate Products with Multiple Categories Using MySQL

Having a database structure that allows a product to be associated with more than one category is a very common scenario in any eCommerce website. However, after working on a couple of truely awful bespoke solutions from other developers recently, whose methods to store and retreive such data were so convoluted, have inspired me to write this article.

Story such data need to not be overly complicated. The following, simple, table structure is required (in a real ecommerce system you would definately have additional fields – these have been omitted here for thae sake of the example):

product_id (PK)

category_id (PK)

product_id (PK)
category_id (PK)

The products_category table is a simple linking table that allows a many-to-many relationship between the product and category table. It contains to two primary keys to ensure every combination of product and category is unique. for example, this table will contain many unique number pairs and a row may be 1,4 or product_id 1 and category_id 4. The files to create and populate this table structure with sample data can be found here.

Now it is simplay a case of running a series of MySQL statements (I’d advise converting them to stored procedures for more security and better application seperation) to retreieve the appropriate data. For example:

Products Within a Certain Category (E.g. category_id 1):

SELECT p.product_id, FROM product p
INNER JOIN product_category pc
ON p.product_id = pc.product_id
WHERE pc.category_id = '1';

Count Products Within a Certain Category (E.g. category_id 1):

SELECT COUNT(p.product_id) As myCount FROM product p
INNER JOIN product_category pc
ON p.product_id = pc.product_id
WHERE pc.category_id = '1';

…and that’s it. Extremely simple, can be expanded to any eCommerce system and not convoluted at all :)

Multiple Categorisation for SEO

A very common technique in ecommerce, is for products to be assigned a single category – part of the filing cabinet approach to site development. This works for niche ecommerce stores, but not for the majority. For example, a tshirt might belong equally in the following categories:’ red tshirts’, ‘logo tshirts’, ‘mens tshirts’ etc. Additionally there are times when it makes sense to have a multiple categories for a product and can help with conversions(a totally different topic).

The special care of multiple categories and SEO is that category pages contain a huge amount keyword rich anchor text. Yes, the majority of ecommerce software and system will allow filtering of results, but the canonical url tag is often used and results in messy links that are not ignored by search engines.

The major issue here is duplicate content – frowned upon by Google and can cause real issues for your site. Yes, a small numbers of pages is within acceptable limits, but when you have store that has hundreds of products duplicate content really can become an issue.

Using our tshirt example from above, say we place a product called ‘super baggy tshirt’ into the ‘red tshirts’ and ‘logo tshirts’ categories – the following two urls would be produced by our ecommerce software – the below structure is very common):

At first glance, this all looks well: SEO friendly URLs, well structured, organised and keyword rich. All this correct, apart from the fact that both URLs represent the same product – here is our duplicate content issue. The duplicate content issue will get worse if the product is placed into more categories.  The easiest solution is to rewrite our product URL to something much simpler:

This will allow us to place the product into as many categories as we need without creating any duplicate content at all – there will always be a single version of the product URL.

Create a CSS Hover Effect Image Gallery

After browsing through a a few web portfolios lately I’ve noticed a rather noce efefct – whereby when the user hovers over a thumbnail an image appear – this may be a zoom icon (for images) or a play button (for videos). In thus article I’ll quickly run through the simple steps on who we create a a funky css hover effect image gallery. This is a very useful technique for any sort of site that display thumbnails links.


<div class="thumb_wrap">
<a href="#link" class="thumb_link">
<span><img src="play.png" alt="play" class="play_video" /></span>
<img src="thumb.jpg" alt="thumbnail" />

I’ve simply nested a span tag containing the hidden play button. Additionally, to keep everything XHTML valid, the hyperlink doesn;t contain block level elemnts.


a img {

.thumb_wrap {
margin:0 25px 0 0;

img.play_video {
position: absolute; 
margin:40px 0 0 80px;
display: none;}

The CSS is simply sets the image’s position absolutely (to ensure nothing gets pushed out of line).

The JQuery

The give the show effect a nice fade in style and in order the show our hidden image I’ll add a small piece of JQuery that finds the image within our span tag and fades it in. The latter is done when the user hovers over the image, when the mouse leaves, the image is hidden again. The folllwing would go within the head tag (I’ve also let Google CDN host my JQuery file):

<script type="text/javascript">
$(document).ready(function() {




…..and that’s it. You now have a cross browser compatible (IE 6 plus) image gallery effect, that is very easy to implement. See the image gallery in action.

PHP Caching with PEAR Cache Lite

Last week I was given the task my a client to speed up their website – they had paid for literally a single hours work, so not much time at all. The site in question was a company website that had various dyamic boxes of content – namely an area for latest events, latest news and latest clients – aswell as a custom content management solution running for the main page content. Additionally, the database is hosted by (for me), argueably the worse and slowest webhost around – – so database lookups are slower than usual to begin with.

Each time a page was served, many unecessary requests were being made to the MySQL database. The site gets quite a lot of passing traffic from search engines, with all the content be created byn the site owner. As a result, databse lookups for the same content each time as not needed and some simple caching was to be used – nameley, PEAR Cache_Lite.

PEAR Cache_Lite is a small yet powerful PHP caching system that will cache (or save on disk) our dynamic PHP pages. Subsequent requests for complex and database intensive pages are not required due to our cache. This will speed up the site no end.

Firstly, you’ll need to download the latest Cache_Lite package and include the file Lite.php on your page. Also, create a folder called ‘cache’ within your site structure. The general idea of Cache_Lite is very simple, giving each page a unique ID – there is no set rule for this and the creation of this ID is left to the developer.

The actual code to cache a complex page is very simple:

Continue reading

W3C Validation and SEO Benefits – My Opinion

The link between full W3C Validation and it’s important upon SEO is commonly discussed topic and a huge taboo. This is the notion that  having a valid site according to the W3C Standards is either critical (or not) to your website’s SEO.The first thing to note that a site passing W3C Validation will have met the following criteria: will not use depreciated tags and will not have syntax errors – essentially a syntax check.

I physically cringe when I hear quotes such as ‘valid xhtml will help your users’. Valid xhtml will not help your users, to help your users a site needs to adhere to web coding standards – this is an entirely different beast. The main difference here is the practice of seperating content from presentation, thus giving the content increased meaning. For example, a page using tables to layout the whole web page would not adhere to web coding standards because using tables for layout is semantically incorrect and requires a lot more code. Tables should be used for tabular data, simple. Another example is the use of paragraph and header tags. Visually they are very similar but have a very very different meaning sementically. However, yet again, semantically incorrect pages will pass validation. The main Google webpage doesn’t even validate (interestingly, Google does’t even quote html attributes in order to save on page size). In my opinion, as long this is the case W3C validation will be a none issue, SEO wise.

Understanding which semantic elements add value to the document will affect the onsite of a website and is an SEO ranking factor.I have read several artuicles that describe W3C validation and SEO as a match made in heaven, this simply isn’t the case, although web semantics and SEO are.

There are many websites (40% is a figure thrown around a lot) that do not validate, yet perform quite well in search engines as they have a range of high quality content. Take a quick example. I searched for a very competitive term “houses”. The number one result was Rightmove even has an authorative listing for that term too – SEO wise there can’t be too many issues here. Running that site through the validator throws up 33 errors and 22 warnings. – see the result. These are mainly smaller syntax errors that quite rightly, the developers of that site have ignored. There are endless examples where sites a lot worse appear at the top of the SERPs, even though they fail to validate and sometimes, don’t follow web standards at all.

Continue reading

PHP Paging with Caching

The majority of PHP paging script with contain a request to the database for a total row count. This is perfectly acceptable if you script needs an exact and accurate results count. However, most sites don’t need a dynamic count and the total results count represents an uneeded database request. On busier sites this effect can become quite limiting and will slow down you scripts.

As an example take a website that gets say 10 hit per second, withouit caching this represents 20 (10 hits on your database and 10 hits on your database to fecth the result set) hits per second to your database – on larger sites and larger result sets this effect is amplified. However, by simply caching the total number of rows returned you can cut the requests to your database in half.

Google uses a caching system on their results (albeit more more complicated) and they never retuirn the exact amount of results (the perforamnce hit on a site as big and busy as Google would be absolutely huge!). Instead they present results as: “results 20-40 of about 248,000″ – with figure of 248,000 coming from an estimated cache value.

To cache the number of results the script would simply store a count of the total number of records in a SESSION variable (assume the cached session value is called “totalResults”. You could also store the result as a COOKIE that expires in the future, to force an update the cached number of rows. Using sessions, the code is very simply:

if( !isset($_SESSION['totalResults']) ) {
  //Code to query your database for a row count
} else {
  //use the total record count directly from the session variable
  $myPagerObj->pageSomeData($_SESSION['total_records'], $perPage, $curPage);

It would also be wirth doing some validation on the cached page value, for security. However, the latter would usually be done directly in you’re paging class.

JQuery Hover Effect Image Gallery For eCommerce

web design talk jquery galleryAfter searching  for a simple jquery image gallery for an online store I decided to make my own. There were several solutions that were close to what I wanted, but quite there. The project required an simple large vierw of an image with multiple thumbnails below, when hovered upon switched the large image. The requirements were as follows: cross browser compatible (IE6 plus, Chrome and Firefox – all the major browsers), have a nice fading effect between image changes and be totally degradable if JavaScript was turned off.

First of all, take a peek and the finished JQuery image gallery – I’ve put the gallery in context on a product detail page for an ecommerce store.

JavaScript and JQuery to the Rescue!

JQuery was the JavaScript framework of choice and made it easy to get things up and running. Techniqually the same effect can be achieved without JQuery, but for simplicity I’m using JQuery. The code is quite easy to follow and I’ll just pickup  up on the main parts.

Firstly we’ll start off with the HTML – simply two dividers, with an unordered lists for the thumbnail images:

<div id="bigpic" class="b"><img src="images/big/iphone-3-big.jpg" alt="iPod Shuffle 16GB Zoom View" />
<p id="desc">iPod Shuffle 16GB Zoom View</p>


<div id="thumbs">
	<li><a rel="images/small/iphone-1-small.jpg" href="images/big/iphone-1-big.jpg">
<img src="images/small/iphone-1-small.jpg" alt="iPod Shuffle Front View In Blue!" />
	<li> <a rel="images/small/iphone-2-small.jpg" href="images/big/iphone-2-big.jpg">
<img src="images/small/iphone-2-small.jpg" alt="iPod Shuffle Dual View Grey!" />
	<li> <a rel="images/small/iphone-3-small.jpg" href="images/big/iphone-3-big.jpg">
<img src="images/small/iphone-3-small.jpg" alt="iPod Shuffle 16GB Zoom View" />

The main image is housed in the divider with the id of ‘bigpic’. I’ve also added a description below the big image – this will change when the image is hovered over to the thumbnail alternate text. Each thumbnail link goes directly to the enlarged version of the image – this way, the gallery will still work when JavaScript is turned off.

The JQuery Magic ….

Right after including the JQuery library (I recommend you make use of Google CDN for this – there are many reasons to let Google host your JQuery files) I have included an int,js file – this contains all the gallery JavaScript. The int file is a small file that catches a hover on each thumbnail and switches the main gallery image (Our ‘bigpic’ divider). All the code is contained within the mahic document.ready listener. The first half of the file catches the hover on a thumbnail:

$('#thumbs ul li a').hover(
		function() {
			var currentBigImage = $('#bigpic img').attr('src');
			var newBigImage = $(this).attr('href');
			var currentThumbSrc = $(this).attr('rel');
			switchImage(newBigImage, currentBigImage, currentThumbSrc);
		function() {}

Here we are getting the currentBig image href, the new big image (from our thumbs href) and current thumbnail src. The second empty fucntion is included to say ‘don’t do anything when hovering away’. Exclude this empty function and the hover event will continue to fire when you leave the image. Now we have these three variables we pass them to our switchImage function, code below:

function switchImage(imageHref, currentBigImage, currentThumbSrc) {

		var theBigImage = $('#bigpic img');

		if (imageHref != currentBigImage) {

			theBigImage.fadeOut(250, function(){
				theBigImage.attr('src', imageHref).fadeIn(250);

				var newImageDesc = $("#thumbs ul li a img[src='"+currentThumbSrc+"']").attr('alt');



This is quite self explanatory. The first check made is that the current big image is not the same as the target big image – if this was true we would fade in and out the same image, which leads to a rather weird looking effect. If both paths match, the user has hovered over the thumbnail of the current big image (in this case nothing would happen). Hovering over any other image will result in the current big image fading out, setting the big image src to the src from the thumbnail (the new image) and populating our description paragraph.

Using the Gallery in a Production Website

In the example 3 static large and small images have been manually added for simplicity. In a real website, maybe an online store, you would retrieve this information from a database. Another thing to note is image sizes. I always find it useful to let users upload whatever file resolution they want, giving them the exact pixels as a recomendation. To ensure that a particularly large file wouldn’t break the layout I tend to sue image resizing scripts, such as the excellent smart image resizer from shifting pixel – uploaded images can be automatically scaled to dimensions of your choosing.

Also, at some point I’ll learn about making your owns plugins for JQuery and turn this into a self contained plugin :)

There’s not a lot more to this to be honest. tested in IE6, IE7, IE8, Chrome and Firefox – all working nicely.

Take a look at the final result or download the source files. Enjoy!