This website stores cookies. Click here to accept them.cookie information page

all about caching

31st December 2011
Categories: caching, php, programming

Caching is when the web server, the browser, or even an intermediate server store a copy of an image, javascript file, css file, or html page, in order to prevent the browser from putting too big a load on the web server by requesting the same page multiple times - for example if you're browsing around a site and frequently return to the home page, or if all of the pages use the same css stylesheet.

So that's a good thing, right?

Unfortunately caching can inconvenience the web developer quite a bit. Take for instance, a website with a little "your basket" sign in the top right corner, informing the user that the basket contains 1 item. When the user hits the home page again, they won't particulalry understand if the sign now says "nothing in your basket". Or take the developer who's designed a makeover for a website, changing the css. They don't want users who are frequent visitors to come back to the site and get a mishmash of content and styles because the css won't update automatically.

Fortunately there are ways around caching problems, and ways to give developers control over caching important elements of a page without caching everything.

Within the page HTML, if you don't want the browser to cache the page, you can add a meta-tag in the page header:


While the browser understands this, however, an additional HTTP header is required in order to make sure that intermediate servers understand the requirement not to cache. In PHP:


header("Cache-Control: no-cache, no-store");
header("Pragma: no-cache");


In Classic ASP:


Response.Expires= -1
Response.AddHeader "pragma", "no-cache"
Response.AddHeader "cache-control", "no-cache"


This doesn't solve the problem of cached css. Luckily, there is a very simple solution when you've just made changes to the css:

<link rel="stylesheet" href="style.css?version=2" type="text/css">

This stylesheet reference says "style.css?version=2" instead of just "style.css".  The browser has to assume that these two files are different, although if you haven't done anything fancy with intercepting calls to css files, they are in fact exactly the same file.  Once the browser has grabbed the latest file off the server by requesting style.css?version=2 then it has that file, and won't need a new one until you change the version number in your html reference to it.

But what about the benefits of caching?

We seem to have overturned the point of caching, at least with PHP pages, so how do we make up for it? My answer is to cache specific portions of the page, i.e. the ones that don't have to be up-to-the-second, and may involve a complicated set of SQL queries to get the information out. You can turn to a commercial caching solution for this, or create a cached content table which you manage yourself. Bear in mind that this will grow and need to be tidied regularly. The code below doesn't supply the housekeeping solution.

First, write the function that gets all the content. Then, when you want to write out the content, instead of calling that function, see if a cache exists. Use some unique code for your content, and call this function:

static function GetCache($UniqueRef, $MinsToCache=3000)


$sql='select cachevalue,lastcached from cachetable where   uniqueref='.MySQuote($UniqueRef);




return false;





return false;


return $aRow['cachevalue'];




If the function returns nothing, call the content-generator function to get the content, and before outputting, cache it - something like:


static function DoSomeCaching($UniqueRef, $CacheValue)



$sql='UPDATE cachetable ';

$setsql=' SET uniqueref='.MySQuote($UniqueRef);


$setsql.=',lastcached='.MySQuote(date('Y-m-d H:i'));

$sql.=$setsql.' WHERE uniqueref='.MySQuote($UniqueRef);





$sql=' INSERT INTO cachetable '.$setsql;




The MySQuote() function is a mysql single quote escaping function - replace calls to this with your preferred method.

Images and the web

30th December 2011
Categories: basics, images

When adding an image to a web page, you'd be forgiven for thinking that you simply fire up your favourite content management system and upload the image, or add an image element to your HTML like so:

<img src="sunflowers.jpg">

Apart from design considerations, which we won't cover in this article, there are various practical considerations to be taken into account, including format, quality, and size.

Image format and quality

Web images come in a variety of formats for the web, but there are three popular ones: GIF, JPG (or JPEG), and PNG.

Both GIF and JPG are 'lossy', that is, from an original photo, saving as a gif or a jpg will lose some information.

GIFs take out image information by reducing the number of colours to 255.  So for example in a photograph with gradients (see below), the GIF version will cut out certain colours, losing the gradient effect (see inset).

png image of ship with inset to show gif gradient

GIFs are most useful for cartoons and other images with low colour resolution.  Here they come into their own, offering the best compression from original images, which means faster downloading on a web page.

JPGS offer a good compression ratio for photos and detailed images.  When saving a jpg using most software you are offered a quality option, 0-100%, which also determines how much the image is compressed.  JPG compression is lossy, but at 100% it is not noticeable.  At 50%, however, you get some odd 'jitter' effects such as shown below (jpg inset):

ship png with jpg inset

PNGs are not lossy, but may not always offer the best overall compression, although it is worth experimenting with a given photo.  Generally speaking, slightly low quality JPGs are best if you want photos on your website but want to reduce loading times.

Image size

It is best to size images to the exact pixels specification before inserting into a web page.  For example, if  you add a 100px wide image to your web page and then ask the web page to size, using the following code:

<img src="sunflower.jpg" width="250px">

Then the browser is downloading the whole image (which could be 1MB or more in disk size) before resizing when it gets shown.

In addition to increasing download size, if you don't resize images yourself, you're not in control of the resizing process.  Generally, photo resizing programs give you a couple of options: cubic and linear.  If you're resizing down, linear is often best, but again it's good to experiment with the specific image. Resizing up isn't generally a great idea, but we've found that cubic resizing, in small increments up to your chosen size, generally gives the best results.



www and non-www

28th December 2011
Categories: php, seo

While most websites serve up exactly the same web pages on the www and non www versions ( and it is good practice to have one 'canonical' version of your website and divert the other version to it, as search engines have traditionally viewed the two versions as duplicates (which isn't good) and having one route to a 'resource' narrows down the margin of error if there are changes to the way you serve up web pages.

In php you can divert one to the other using the following code:

// redirect to www if not there already
  && (strpos($_SERVER['HTTP_HOST'],'')!==false)
  Header( "HTTP/1.1 301 Moved Permanently" );

If you have access to the DNS for your website you may wish to point the non-www site at a different location altogether, with just one index.php file containing the following code:

Header( "HTTP/1.1 301 Moved Permanently" );

Note that the header containing the 301 code is important for search engines; in almost all cases you should use a 301 (permanent) redirect as it tells search engine spiders that the old url is redundant and the new url should be credited with any 'kudos' that the old url ever had.

A slightly neater way of doing the redirect is to do it outside of PHP code, in your .htaccess file if you are running on apache and you have permissions (via the apache config) to do it:

# rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
# non www to www
RewriteCond %{HTTP_HOST} !^www\.mygreatwebsite\.org$
RewriteRule (.*)$1 [R=301,L]

On IIS you can do it using the website properties within IIS manager.  Just add another website for the non-www version, and once added, in the website properties, instead of serving web pages from a folder on your computer, choose to make it a 'redirection to another URL'.  Remember to take the non-www version off the host headers accepted by the www version (website... advanced button).

What is jQuery?

21st December 2011
Categories: basics, javascript

I'm building a shed in my garden. What I need is to put bikes, a lawnmower, a few tins of paint, a toolbox and some random junk under cover. That's the primary aim of the project.  The seconday aim is that it mustn't look too shabby.  And finally it mustn't be a lot of work to put up.

Now I know that the raw materials for building a shed are wood and nails, and maybe some glue. But it would be great if some of the pieces of wood came stuck together already, so that I didn't have to do so much hard work to achieve my goals.

Enter the pre-fabricated shed, and ta-da!  It takes less than half the time.

jQuery is basically a pre-fab shed for Javascript. Someone has spent a lot of time and energy building commonly-used routines and functions to do things like showing and hiding bits of web page, calendar controls, and that kind of thing, and once you have jQuery and some simple documentation you can access them very easily without all the hard work.

Take 'lightboxes' for example. They are a popup window in the middle of your web page to show an image. They can be part of a gallery and include 'previous' and 'next buttons'.

If you google 'jQuery lightbox' you'll get an example of this javascript at work, and a download link which gives you the jQuery core library and the lightbox library, and some sample code to get you started with your very own lightbox code.

The way a lot of jQuery works is by modifying attributes of existing HTML.  Say you have some HTML which looks like this:

<div class="someclass">
     <a title="Some random picture" href="pic.jpg">
        <img src="thumb.jpg">

The jQuery code for turning your thumbnail picture into a link to a lightbox happens in the Javascript at the top of the page, where you call a function to modify the action of the anchor tag.  Most of the work that's done is hidden from you (the coder), you simply call a jQuery function to turn  the div into a lightbox gallery.

What is Javascript?

14th December 2011

Not to be confused with Java, Javascript is a computer language intended mainly for use on web pages. Unlike, for instance, PHP, ASP and server-side Java, which give the web server computer instructions and produce web pages, Javascript gives the client's computer instructions, which are only processed when you're viewing the web page in a browser.

To put it simply, a PHP script may connect to a database, create a web page and send it to the browser; Javascript runs on the browser and is mainly used for visual effects.

Here is a sample web page with some Javascript in it - you can save it as an .html file and run it and it should work in any browser:

<!DOCTYPE html>
<script type="text/javascript">

function doThings()




<button id="btn_things" onclick="doThings();">click here</button>


First of all, the page loads into your browser and you see a button saying "click here".  The button has an attribute (which is not visible ot the user) called "onclick".  This is the name of an event, and you can see a complete reference of html events on the w3schools website.

When the event is triggered (by clicking the button), the browser looks up the value of the onclick attribute and finds that it's "doThings();".  This tells it to look for the "doThings" function in any script on the page.

function doThings()

The first instruction in the doThings() function is an assignment... assigning the value "yellow" to something called "document.getElementById('btn_things').style.color".  The document.getElementById is an instruction to find the object in the HTML of that name, and when this is found, the instruction references the style property of the object and the "color" property of "style".  Properties of elements in an HTML document can be looked up again on the w3schools website.

That very short demonstration is an introduction to inserting Javascript code into an HTML page. We will come back to Javascript in future posts to discuss how to make it work harder!

How do you save data to a database?

10th December 2011
Categories: basics, databases

Databases are a tool for data storage and retrieval.  They tend to be more useful than data files (i.e. simple text files) because they can be queried very quickly, due to the use of indexes. But it's worth noting that databases really are glorified data files, with some housekeeping processes and query tools to make them easier to use and maintain.

Let's stop for a moment to talk about indexes.

If you've ever read a reference book you'll know roughly how an index works: you can find an important word quickly in the index because the index is small. The index points to a page in the larger body of the book. But once you've found your word in the index, you can find it quickly in the book because you can quickly thumb to the right page. 

This is exactly how database indexes work, and why from billions of web pages, search engines can find what you're looking for before you've finished typing it. It is why any web developer worth his salt (and given a decent server) can make a website go fast... but I digress.

How will a database help me?

Databases not only do the indexing and lookups for you, a relational database will let you query by linking tables -- for example customers and orders. If you have a customer table with all the relevant information about a customer - email, contact details and so on, you may not want to replicate this inside every order. So you have two data files (or 'tables', as they're known in the business) and you can join them both in a query, like this:

SELECT customer.firstname, customer.lastname, order.orderid FROM
customer INNER JOIN order on customer.customerid=order.customerid 
WHERE customer.lastname='Smith' 

The lines above are called a 'query', and this is sent to the database system by whatever programming language you use, from one program to another on the same computer, or over the internet.  The database server then interprets the query (at lightning speed) and sends the results back to the software.

So instead of writing software specifically to query each table and to match up the results, you simply phrase the query for the database server to understand.  And instead of goint through each line in the data file checking against your search criteria, you leave the job to the database server and its lightning-fast indexes.

What are the choices?

There are too many choices of database server to mention here, but I will name a few:

MySQL is an open-source product and the world's most popular web db, supporting the vast majority of the world's data-driven websites.

MS SQL is Microsoft's database server, very robust and full-featured.

MS Access is a desktop database, not suitable for large or web-based applications.

Oracle is the traditional choice for big corporate finance systems.

Where do I go from here?

For a first time web developer I'd recommend getting started with MySQL - whether using PHP or ASP. Most web server installations come with MySQL installed, and for ASP you can download "connectors" from the website.  For windows desktop use, WAMP (Windows, Apache, MySQL, PHP) is a real life-saver and installs all of the main components for getting a dynamic website up and running.

What's a Content Management System?

9th December 2011
Categories: basics, cms

A content management system (CMS) is a way of adding pages to your website without editing HTML.

CMS's have several advantages over HTML editors such as Dreamweaver:

- They allow the separation of design and content. When you have designed your website, you don't want content authors to make constant design changes. Design should come about through a completely different (and well thought out) process.

- They (typically) organise the navigation for you. As a very simple example, when you add a news item to your website, it should exist as a link on the home page , and as a story page.

- They allow your content to exist in more than one place. For instance a product could exist in more than one category page without you having to re-type the details, or your testimonials could appear on every page of the website without any extra work.

One of the simplest CMSs, but a reliable and well-supported one, is Wordpress. Wordpress has become almost synonymous with blogging, despite some search engine compatibility flaws such as allowing search engines to index duplicate content, and the limit of one blog per site. 

Joomla, Drupal, and Concrete5 are also well known CMSs, but there are hundreds of CMSs on the market, each with its own strengths and weaknesses.

Oxford Web's CMS, Oxebiz, is feature rich, in that it combines CMS, blogging, and customer relationship management in one control panel, and uses industry standard features such as the TinyMCE rich text editor.

As a developer, whichever CMS you choose, it takes time to get to know its quirks and the best methods of adding functionality, but once you have done that, you have a very powerful tool not just for editing websites but also for creating them, as CMSs normally provide a framework for getting up and running with a website, to which you add your header/footer HTML, CSS etc.

What is a web server?

4th December 2011
Categories: basics, web servers

If you've taken the journey through our technical blog from the beginning, you'll have an understanding of what HTML is and how to use it to build websites. We haven't yet covered how web pages get from A to B on the internet, so that's our next topic.

If you try out some of the HTML and CSS we've discussed and save it in a text file called webpage.html (make sure it's a text-only file, so use notepad or dreamweaver, or your favourite equivalent) then you will be able to double-click that file on your desktop (or wherever you've saved it) to see the resulting web page.

At this stage in the life of your HTML file, nobody but you can access it. It's a web page, therefore, but it's not part of the internet.

In order for this web page to become part of the internet, it doesn't just need to be on a computer connected to the internet. It also needs a web server, a computer whose purpose is to serve web pages to other computers. Web servers are usually Linux or Windows machines (there aren't very many Mac ones) with a program running all the time (also called a web server, confusingly) which listens for new requests and decides what to do with them.

For the web server software to be able to receive any requests on a domain name like, it doesn't just need to be connected to the internet; your browser needs to associate it with that domain name. This job cannot be completed on the server itself; you need to add entries to something called the DNS system. You can do this via a domain name registrar (in other words, the people who sell domain names, 123-reg and sitelutions being examples).

Once you've hooked up the doman name with the address of the web server (the so-called "IP" address), a process with which the domain name registrars will help you, your web server will start receiving requests - now it just needs to process them.

Web servers need to know where the web pages live (they won't look all over the computer; they need to start from a particular folder - that's called the web root), and they also need to know a bit about how you want to process different file types. For example, your HTML file might just be sent as-is to the user requesting it, for their browser to display. Other files, like PHP, may include instructions (lines of code) for the web server to process first - including receiving input, calculating, and fetching content from different places.

The web server processes whatever it needs to process, calling on other software (like the PHP interpreter) in the process, and finally serves up your web page. If your web page refers to other files (like a css file or image files, for example), the browser will make another request to the web server, and the web server will go through the request processing again and serve up another file. 

What are PHP, ASP and Java?

1st December 2011
Categories: basics, php

What are PHP, ASP and Java?

Having read the previous posts, you'd be forgiven for thinking that the world wide web is just a collection of interlinking documents.

That's how it started, of course, but now we have much more than that.

What links the static documents stage to a more interesting world wide web, where people can send and receive information, buy products, and generally interact with the web pages they visit, is software especially developed for building web pages.

There are three main contenders in this area:

- PHP (An open source system which stands, confusingly, for PHP Hypertext Preprocessor)

- ASP (Microsoft's 'Active Server Pages', which support various languages, including C# and Visual Basic)

- Server-side Java (another open source system originally developed by Sun) 

I'm calling them "systems" rather than "languages" because getting them working is a bit more complicated than writing software and sticking it in a compiler... but that's too much jargon already, please bear with me...

My aim in this article is to explain what these systems do that HTML doesn't, so rather than delve into the individual languages, I'll write some pseudo-code (pretend software code) to explain.

Say, for example, that you wanted the user to tell you their name. In HTML you can ask for their name - the code would look something like this:

<form> What's your name? <input type="text" name="namebox"> ... </form>

But HTML has no way of capturing the name once the user has typed it in, so we need a programming language so do something like this:

User_name = Get_the_user_input("namebox")
Print "Hello " + User_name

User_name is what's called a variable, in other words a placeholder for a value that can be changed at any time.

Get_the_user_input is pseudocode (pretend software code) for however you would retrieve some user input in your language of choice.

Of course, PHP, ASP and Java can do a lot more that retrieve input. They can store information, manipulate information, and output information. And like most computer languages they can make decisions and go around loops. This gives them the ability to do pretty much anything you want a website to do, given careful planning and the time to code.

All three also have the ability to create and manipulate "objects", a special kind of variable designed to mimic objects in the real world, which can have multiple properties and functions, and so can speed up the process of programming... but more on that in another post!

© Alberon Ltd 2018

8 Standingford House
26 Cave Street

01865 596 144

Oxford Web is a trading name of Alberon Ltd, registered company no. 5765707 (England & Wales).