Ashley Sheridan​

Stylesheet Switcher

Posted on


One drawback to alternate stylesheets on a website is that no browser I've seen allows the newly selected stylesheet to persist through the browsing of that site. As you move from page to page, the default style takes over again. This was particularly annoying for me, as I was in the middle of testing out a new stylesheet on my site as a demonstration, and each time I navigated to a new page, I'd have to use the browsers menu option to change the style all over again!

This technique makes use of cookies to allow the styles to persist. There's no major disadvantage to the visitor if they delete the cookies, as nothing important is lost, and it's a simple matter for them to click the link setting the new style whenever they wish.

<?php $styles = array('main' => 'Pastel', 'modern' => 'Modern'); session_start(); if(isset($_COOKIE['style'])) { $style = $_COOKIE['style']; if(in_array($style, $styles)) { $_SESSION['style'] = $style; } } if(isset($_GET['style'])) { $style = $_GET['style']; if(in_array($style, $styles)) { $_SESSION['style'] = $style; setcookie('style', $style, time()+60*60*24*30); } } if(!isset($_SESSION['style'])) { $_SESSION['style'] = $styles['main']; } foreach($styles as $key => $value) { $alternate = ($_SESSION['style'] == $value)?'':'alternate '; print "\n<link rel=\"{$alternate}stylesheet\" href=\"styles/$key.css\" title=\"$value\"/>"; } ?>

The second line is just an associative array of your stylesheets with their base filename as the key. This is so that you can call your stylesheets whatever you want, while some systems will limit you on what characters you can use in a filename.

The first if statement checks to see if a style has been set at any point inside the $_COOKIE array. If one is found, it checks to make sure that the specified style is in the list of styles you created in line 2. This is more to prevent tampering with the cookie for malicious purposes than to prevent an old stylesheet being used if you've removed it from the list. The second if statement does much the same as the first, but checks to see if one has been specified in the $_GET array. This means that if one was found in the cookies, but a link was cicked which sets a new one, the link takes precedence. If a link was clicked, it updates the cookie to reflect this.

Finally, another if statment checks to see if a style exists in the $_SESSIONarray. This is mainly for first-time visitors, as they will have neither the cookie or $_GET parameter set, so the value in $_SESSION['style'] needs to be set to some default.

Finally, the foreach loop goes through all the available styles, and outputs the HTML necessary for multiple stylesheets. All the stylesheets except the one that was chosen will have an alternate attribute set, which instructs a browser to make this available as an alternative stylesheet, but not the primary one.


Leave a comment