Flickr™ last.fm

Dynamic CSS using PHP Power - Thursday 1st September 05

A trick I like to use is making my style-sheets dynamic using php. This gives the user something slightly different every-time they visit your site. There are two main methods of making your style-sheet get parsed through the php parser. Both of them are slightly different with pros and cons.

The methods

Apache AddType

This method works by adding the following line in a htaccess file.

AddType application/x-httpd-php .css

Pro's

The main pros of this method are: You don't have to change the extension on your style-sheet which could have cause some pages breaking. The second pro is if someone downloads the CSS file it will download as a normal CSS file rather than a php file.

Con's

The main bad point with this method is you have to be careful with all of your style-sheets. For example if you have more than one style-sheet in the directory you have to add a php header to all of them.

Changing the Extension

This method simply requires you to change the extension of the CSS file. For example styles.css would change to styles.php.

Pros

This method is good if you only want to make the one style-sheet dynamic.

Cons

If you don't have Multiviews or Mod-Rewite turned on then you would have to change all the files that reference this style-sheet. This file also doesn't look like a style-sheet as it has the wrong extension.

Adding the dynamic bits

There are many different ways of doing the next bit. This is just the way that works for me and is easy to follow. When you use dynamic style-sheets you will usually want to apply more than one change. This enables you to say change all of the colours on your page.

First things first, in the top of your CSS file you need to add the header

header('Content-type: text/css');

This will let browsers see the file as a style-sheet otherwise it gets parsed out as text/html. From here it is pretty straight diving. Just randomly set a set of colours.

$i = rand(1,3);
switch($i):
case 1:
    $background =  "light blue";
    $h1 = "blue";
    $h2 = "dark blue";
    break;
case 2:
    $background = "light red";
    $h1 = 'red';
    $h2 = 'dark red';
    break;
case 3:
    $background = "light green";
    $h1 = 'green';
    $h2 = 'dark green';
    break;
endswitch;

Then echo them in to the style-sheet with a simple echo:

body { background-color: <?=$background ?>; }

Hey presto you have a dynamic style-sheet and look like a mega-css-pro.

© 2012 Edd Sowden