Webforumz Newsletter - November 2007

Tutorials

Dynamic Stylesheet Switcher in PHP

In this constantly fast paced place we call the World Wide Web it is an important feature of any website to be able to offer the maximum amount of interactivity to your users. I am going to show you how to create a dynamic stylesheet switcher using PHP so your users can choose how they view your website!

First of all you'll need to create a basic HTML page and your CSS stylesheets for it. In this tutorial I am going to use 3 stylesheets as an example. Modern, Plain and Accessible.

The PHP itself is actually relatively simple. We will be using hyperlinks and PHP's GET method to process them.

Setting Up

First of all you must set up the stylesheet switcher on your HTML page. To do this you need to create links to each stylesheet, you can display them as you wish either in text or images. We are going to echo out the PHP_SELF variable, this will display the current URL. Then we use the string concatenation technique to append the name of the stylesheet in a GET variable like so: "?style=name-of-your-stylesheet".


<a href="<?php echo $_SERVER['PHP_SELF'].'?style=modern'; ?>">Modern</a>
<a href="<?php echo $_SERVER['PHP_SELF'].'?style=plain'; ?>">Plain</a>
<a href="<?php echo $_SERVER['PHP_SELF'].'?style=access'; ?>">Accessible</a>
    

Save your HTML document as index.php.

Also create a second HTML page with the switcher on and name this page2.php. Create a hyperlink from index.php to page2.php and vice versa.

Setting the styles

Once that's done we can get into the proper PHP. Open a new PHP file, call it 'switcher.php'.

First we will set a variable called style and give it the value of your default stylesheet


<?php
// give the style variable the filename of your default stylesheet
$style = 'modern.css';

    

Next we must check to see if "?style" is set in the URL and set the style variable accordingly afterwards. Add this code below your previous PHP:


if(isset($_GET['style']) &&($_GET['style'] == 'modern')) {
// if modern has been clicked on assign the filename 
//modern.css to our style variable $style = 'modern.css'; } if(isset($_GET['style']) &&($_GET['style'] == 'plain')) { // if plain has been clicked on assign the filename
//plain.css to our style variable $style = 'plain.css'; } if(isset($_GET['style']) &&($_GET['style'] == 'access')) { // if access has been clicked on assign the filename
//access.css to our style variable $style = 'access.css'; } ?>

Go back to your html document, index.php. Now we need to apply the correct stylesheet in the head of our HTML document. To do this normally our line of code looks something like:

	
<link rel="stylesheet" type="text/css" href="styles/modern.css" />

But we need to edit the highlighted code to echo out the chosen stylesheet. We will check if the style variable is set, if it is we echo out the contents of the variable. If it is not set we echo our default stylesheet; this is done to prevent the page breaking in case of an error.

So your code will go in the head section of your HTML. The code should look like this:


<link rel="stylesheet" type="text/css" href="/link_to_your_styles/ 
<?php if(isset($style)) { echo $style; } else { echo 'modern.css';} ?>" />
    

Put this code in the head section of page2.php as well.

We need to link to our PHP page in order for the style switcher to work. This line must be placed in each of your pages and must be at the top of the page before the doctype declaration.

Place this line at the top of our two HTML pages:


<? require_once('switcher.php'); ?>
    

Now we've come quite far and you can test it out.

Hopefully if all has gone well you can click a link and the style will change. If it's not working yet don't worry, just read over the above steps and make sure you got all the steps. If it is working however you will notice that the styles don't follow onto any other pages you visit unless you click the style-changing link again. Get ready to fix that now!

Keeping the styles

Remember earlier I said the call to our PHP file needs to go above our HTML, now we'll find out why! We are going to use cookies to record the style changes, and when setting cookies you must set them before any content is output to the browser or you'll get some nasty fatal errors. We are basically going to set a cookie that lasts 2 weeks based on the chosen style. That way if the user decides to come back a week later they can still see their chosen style without clicking the links.

So enough theory, let's go. We're going to amend what we've already done in switcher.php. New code that you need to add is in bold.


<?php
// set up an if statement to check if the cookie is set
if(isset($_COOKIE['styleSet'])) {
//if it is set assign the value of the cookie to
//the style variable $style = $_COOKIE['styleSet']; // if it is not set then we check for our GET variable using
//the code we created earlier } else { $style = 'modern.css'; } if(isset($_GET['style']) &&($_GET['style'] == 'modern')) { $style = 'modern.css'; // add this line of code to ALL of the if statements
//that we created earlier setcookie('styleSet', '', time()-(60*60)); } setcookie('styleSet', $style, (time()+(60*60*24*7*2)), '/');?>

A quick run through of what we have done here...

We first of all check to see if a cookie is set, if so set the style variable to it's contents else set to default. You will also see within our URL checking if statements something new. We use the setcookie() function and calls the cookie "styleSet", it gives it a blank content and sets it to an hour ago. Basically it clears the cookie called styleSet. This is to get rid of any preset styles and stops errors with the last statement. Make sure this line is added to every if statement used to check the URL.

The last statement will do the same as above but rather than cancel and clear the cookie it will assign the value of $style to the cookie and give it an expiry time of two weeks in the future. Lastly we use '/' to apply it to the whole domain. We add this statement to the very end of our code so that the value of the style variable is stored in the cookie and overwrites any old values.

You're done!

Now if all has gone well you will be able to dynamically switch styles and keep them recorded for future use, all through the magic of PHP!

If it is not working check through each step carefully and make sure you have changed any links to link to your files.

You can also download this zip file which contains a working demo of the stylesheet switcher.