In today’s world adding interactivity to a website is important. In this excellent tutorial our author shows us how to create a Stylesheet Switcher using PHP.

Dynamic Stylesheet Switcher in PHP

By Blake Simpson | March 5th, 2008 |
Print This Article

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. That is why I am going to show you how to create a dynamic stylesheet switcher using PHP, that way your users can choose how they view your website!

First of all you’ll need to create a basic web 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 by creating a style.php page, we then need to link to the page to choose the style. You can display the links as either text or images. We are going link to the PHP page that will do the processing using a GET request "?style=id".

This code should go in your HTML. Below is an example of my stylesheet switcher links:

<a href="http://www.theloop.org.uk/style.php?id=1">Modern</a>
<a href="http://www.theloop.org.uk/style.php?id=2">Plain</a>

<a href=" http://www.theloop.org.uk/style.php?id=3">Accessible</a>

Setting the styles

Once that’s done we can get into the proper PHP. All the following must go in your style.php file.

First of all we will find the page to return to. We will set up a default URL if the referrer cannot be found.

We must check that $_SERVER['HTTP_REFERER'] is “set” (e.g. It is there and able to be used) because some servers do not have it enabled. If we find it is not, the script can then use your default.

<?php
//set a back link
if(isset($_SERVER['HTTP_REFERER'])) {
$back = $_SERVER['HTTP_REFERER'];
} else {
//set a default
$back = 'http://www.theloop.org.uk/';
}

Next we must check to see if "?id" is set in the URL. If not we will redirect back. Add this code below your previous PHP:

//check if id is present and valid in URL
if(!isset($_GET) || !isset($_GET['id']) || !is_numeric($_GET['id'])) {
header("Location: $back"); //otherwise redirect back.
exit; //then exit the script to stop further processing.
}

Next, providing the URL is valid, we will assign the style variable to the id of the chosen stylesheet.

//assign variables
$id = $_GET['id'];

//check the id is not above or below your stylesheet numbers
if($id >0 && $id< =3) {
	$id = $id;
} else {
//if it's not, set the stylesheet to default.
	$id = 1;
}

We now have to set a cookie of the chosen style id to be used when loading the page.

if(isset($_COOKIE['style'])) {
	setcookie('style', '', time()-(60*60));
	setcookie('style', $id, (time()+(60*60*24*7*2)), '/');
} else {
	setcookie('style', $id, (time()+(60*60*24*7*2)), '/');
}

Notice that if the style cookie is already set (Checked with the isset() function) we first of all unset it by changing its date to an hour ago, this will delete it from the users hard drive. We then set the style cookie to 2 weeks in the future holding the number of the chosen stylesheet.

We will then link the user back to the page they cam from:

header("Location: $back"); //redirect back
exit; //exit the script
?>

Working with includes

We now need to create an include file that will be included on every page. This file will decide what stylesheet to link to.

This include must be placed above the doctype. It should be the first thing on every page as it will utilize the session_start() function, which should always be the pages first command. The session_start() function is just a way of saying that this page can use cookies or sessions on it. Without it though, the include file will not work.

Create a new file called styles.inc.php. First of all we check to see if the style cookie is set. Otherwise set a default style.

 //start the session for use with cookies.
// Make sure it is in line with "<?php"
<?php session_start()

//find a style to set
if(isset($_COOKIE['style'])) {
	//we'll come back to this in a second
} else {
	$style = 'style.css';
}
?>

If the cookie is set, we use an if ... else if ... else to determine what style has been set. If we cannot find out, we use the final else to set a default. However, if we can, set the $style variable to our stylesheets name.

<?php
//find a style to set
if(isset($_COOKIE['style'])) {
	$cs = $_COOKIE['style']; //create a short variable to _
                                   stop long typing
	if($cs == 1) { //Use an IF statement to figure out _
                        which style to use
		$style = 'modern.css';
	} else if($cs == 2) {
		$style = 'plain.css';
	} else if($cs == 3) {
		$style = 'access.css';
	} else {
		$style = 'modern.css';
	}
} else {
	$style = 'style.css';
}
?>

Once you have finished this file. Find the line where you link to your stylesheet. My one looks like:

<link rel="stylesheet" type="text/css" _
href="http://www.theloop.org.uk/css/modern.css" />

We will then convert this to use the PHP variable like so:

<link rel="stylesheet" type="text/css" _
href="<?php echo $style; ?>" />

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!

About The Author

Article By: Blake Simpson
Blake Simpson Blake is a computing and web design student that loves to use PHP. His personal website can be found at The Loop.

You can view other posts by Blake Simpson. Or you can visit Blake's website at: http://www.theloop.org.uk/

Comments

  1. Andy said :

    Hi, Thanks for this script, just what I was looking for. Unfortunately I can’t get it to work, do you have an example, or somewhere to download the code?

    Thanks.

  2. Steve said :

    Love the article, but like to read away from the computer. However, your site makes that a challenge. I am a firefox user and when printed half of the content is missing. When I use ie view and print the code sections are cutoff because they are wider than the page. Please consider creating a print stylesheet.

    Thanks and keep the great contetn coming,
    Steve

  3. Karinne Legault said :

    Thank you for commenting! We are presently working on getting that print stylesheet up. I hope to get it working over the week-end. If not, next week for sure!

Do you have something to say?