Build your own PHP style sheet switcher

Want to have a style switcher that lets your site's visitors choose a different style sheet? Want it to work even if there is no JavaScript support? The trick is to use a server-side language like PHP, which is what I used to use for my style switcher.

Note: I have now taken the style switcher offline since I kept forgetting to maintain multiple stylesheets. It's not because having a style switcher is bad or anything.

Using PHP to let the user switch to a different CSS file is nothing new. But it is one of the things that I am often asked about, so I thought it would be good to have a write-up to refer people to in the future.

As I mentioned this will work when JavaScript is disabled. It will not work when cookies are disabled, however. Nothing bad will happen, but it simply won't work and the user will be returned to the same page they were on. Just to make you aware of that right from the start.

I use this style switcher to let visitors switch between two different layouts ("Zoom" and "Normal") here on 456 Berea Street. If you want to let the user choose between more than two stylesheets you will need to come up with a different solution.

I wouldn't call myself a PHP expert by any means, so if you think my code could be improved in any way, please let me know.

To switch styles, all you need to do is activate the link to the styleswitcher. As you may have noticed if you have tried that, the URL that invokes the styleswitcher is always the same. The link leads to a php file that looks like this:

$layout = (isset($_COOKIE['layout']) && ($_COOKIE['layout'] == "zoom")) ? "main" : "zoom";
setcookie("layout", $layout, time()+31536000, '/');
$ref = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "http://{$_SERVER['SERVER_NAME']}/";
header("Location: $ref");

Here's what happens, line by line:

On all pages a check is performed to decide which stylesheet to load:

$layout = (isset($_COOKIE['layout']) && ($_COOKIE['layout'] == "zoom")) ? "zoom" : "main";

If a cookie exists and its value is "zoom", $layout is set to "zoom". Otherwise, $layout is set to "main". At this point $layout contains the name of the CSS file that should be loaded.

Finally, when loading the main style sheet the value stored in $layout is inserted instead of the file name in the @import path:

<style type="text/css" media="screen,projection">
@import '/css/<?php echo $layout; ?>.css';

And that's it. Use it, spread it, improve it.

Posted on August 23, 2006 in PHP, CSS