Posts tagged ‘Style Switcher’

Feb 12 09

PHP Style Switcher

A while ago, I wrote a post on how to create a JavaScript Style Switcher, but recently I found the need to create a PHP based one. There are many ways to do this in PHP using sessions, arrays, cookies, etc. I created one that only takes a few lines of code and is super easy to implement.

This PHP Style Switcher can be done in two easy steps.

Step One: Setting styles

The first step is to create a new file on your server named switcher.php and paste the following code into it:

<?php
/* expire in 1 year */
setcookie("sitestyle", $_GET['set'], time()+31536000);
header("Location: $HTTP_REFERER");
?>

When it’s queried, this file will write a cookie for the user detailing which site style to use. The cookie is set to expire in one year, and then the script sends the user back to the referring page. All of this happens behind the scenes, so the user will never really “see” switcher.php in action.

Telling switcher.php which site style to use is an equally simple matter. You can query it using conventional HREF links in text, images, or even flash

<a href="switcher.php?set=red">change to RED style!</a>

Step Two: Detecting styles

<link rel="stylesheet" type="text/css" media="screen"
title="User Defined Style"' href="<?php echo 
(!$_COOKIE["sitestyle"]) 
?'default':$_COOKIE["sitestyle"] 
?>.css" />

This tiny script detects which style is in the user’s cookies and prints out the result. If the user doesn’t have cookies enabled, or just hasn’t chosen a site style for themselves yet, the script will default to “default.css”.

So there you have it. A cross-browser, backwards-compatible, forwards-compatible, standards-compliant style sheet switcher in just five lines of code. It’s fast, straightforward, and universally accessible because there’s no processing done on the client side.

Here is the code (.zip) as well for you to review.