Another PHP Styleswitcher

By Rob Ballou. October 14th, 2002
(Last updated: May 16, 2007 14:36).

Table of Contents

Skip to next section

  1. Introduction
  2. Step one: The "switcher" code
  3. Step Two: The switching device
  4. Step Three: The Stylesheet Declaration
  5. How to change for old PHP version
  6. Errors you may get
  7. Code updates!
  8. Contact information

Examples

  1. Example 1
  2. Example 1 Source Code

Introduction

Skip to next section

The recent A List Apart (ALA) article by Chris Clark provides the same relative functionality as the JavaScript version also available on ALA.

Unfortunately, the tutorial misses a few helpful points and leaves some gaping holes here and there. So I thought I would share some notes on this. Please realize that this is not to say the ALA article is not good. In fact, with out Clark's inspiration, this tutorial wouldn't even be here.

Firstly, here is an online example of this PHP switcher (source) in action.

Now how does it work?

Back to the top

Step one: The "switcher" code

Skip to next section

The switcher code is the little script that sets the cookie, saving the user's preference.

Create a script file called "switcher.php" (you can save this file anywhere you like on your site).

If you are using PHP 4.2.2, place this code in the file:

Skip this code

<?php
// This array lists the "acceptable" styles
$accept = array('red',
                'blue',
                'green');

// Get style from a query string (e.g. from a link),
// or from a form.
if(isset($_REQUEST['set'])){
	$style = trim(strip_tags($_REQUEST['set']));
}
else if(isset($_POST['set'])){
	$style = trim(strip_tags($_POST['set']));
}
else {
    // Unknown request
    $style = false;
}

// Check if the requested stylesheet is "acceptable"
if(($style !== false) && (in_array($style, $accept))){
	setcookie("sitestyle", $style, time()+31536000, '/', 'yourdomain.com', '0');
}
if(isset($_REQUEST['ref']) || (isset($_POST['ref']))){
    if(isset($_REQUEST['ref'])){ 
        $ref = $_REQUEST['ref'];
    }
    else {
        $ref = $_POST['ref'];
    }
    header("Location: $ref");
    exit;
}
else if(isset($_SERVER['HTTP_REFERER'])){
	// Send the user back to the refering page
	header("Location: ". $_SERVER['HTTP_REFERER']);
	exit;
}
else {
	// No HTTP referrer, send them back to the home page
	header("Location: http://yourdomain.com/homepage.php");
	exit;
}
?>

If you are running a different version of PHP, see this note on the changes you need to make.

What does all this code do? First, as a security precaution we make an array of acceptable values. If we get something else back, we don't set the stylesheet cookie (this keeps people from setting unwanted cookies on a user's machine). Second we check if the request is coming from a form (via POST) or a link (via a query string).

Once we get the requested style sheet and it checks out against our acceptable values, we set the cookie. Then we send the user back from where they came (or to your homepage).

Some helpful PHP documentation links:

Back to the top

Step Two: The switching device

Skip to next section

To give users a way to change the style, you can use the methods described in the article. The script will take either query strings or posted information (from a form).

Back to the top

Step Three: The Stylesheet Declaration

Skip to next section

In your normal file (where the user changes their style) you need to change how your links to your stylesheets are set up. Be sure that your page has the extension ".php" or this will not work.

For PHP 4.2.2:

Skip this code

<link rel="stylesheet" href="path/to/css/<?php
if(isset($_COOKIE['sitestyle'])){ // Use the saved style
  print trim($_COOKIE['sitestyle']);
}
else { // There is not a cookie set, so use this style
 print "defaultstyle";
}
?>.css" media="screen" />

Note: Replace the "path/to/css/" with the path your CSS files. Also, if you look at the example style switcher, I set the two stylesheets as "alternate stylesheet" in every version of the document (look at the source). This allows users to access both stylesheets no matter which they are currently using.

Also, you can use the same php code with <style> tags by using the @import rule. For that I suggest you read, Eric Meyer's article on hiding styles.

Back to the top

How to change for old PHP version

Skip to next section

Older versions of PHP do not have the nice $_COOKIE, $_REQUEST, and $_POST variables. So instead, you need to replace the variables $_COOKIE and $_POST with $HTTP_COOKIE_VARS and $HTTP_POST_VARS, respectively. $_REQUEST is more tricky and you probably should change that to $set rather than $_REQUEST['set'].

Unforunately I can't test this, so please let me know how it works.

Back to the top

Errors you may get

If you get an error saying that your headers have already been sent out, this means that you have outputed text or whitespace before you called setcookie() or header(). This causes problems because both send out HTTP headers, but because there is text before this, the headers have already been sent to the client.

Ok, how do you fix this? Make sure there is no whitespace or text before you call either of these functions. The only place in our example where these functions are used is in the "switcher.php" file, so be sure to check for whitespace before the opening <?php.

Also, parse errors are generally caused by forgotten ";" or misplaced quotes or curly braces. When you get an error like this look at the line number in your script and a few around it. Sometimes it isn't exactly where PHP says the error is.

Back to the top

Code Updates

After looking over some comments in the discussion over the ALA article, I made some changes to the code. You code should still work with the old code, but this may or may not help.

Simon Coggins suggests including a reference to the refering page by using this code (so users can return to the page where they came from):

<a href="switcher.php?set=red&ref=<?php $_SERVER['PHP_SELF']?>">

The code now supports receiving a ref variable from a link (like shown above or from a form). To use it with a form, do this:

<form action="switcher.php" method="post" name="styleSwitcher">
  <input type="hidden" name="ref" value="<?php $_SERVER['PHP_SELF'] ?>" />
  ...
</form>

October 28: I updated this document to include a little note about include the stylesheet in a document.

March 1st, 2003: Fixed a small parsing bug. Thanks to Paul and Stuart for pointing it out (sorry it took so long to fix).

April 4th, 2003: More bug fixes.

Contact Information

Questions? Comments? Feel free to contact me.

Back to the top


Copyright © 2002 Rob Ballou. All Rights Reserved.
Last updated: May 16, 2007 14:36

This page's CSS and XHTML validate. Does yours?