PHP StyleSheet Selector

This Tutorial is showing how to create a simple StyleSheet Selector in PHP.

The best way to allow users to chose an alternative StyleSheet is hardly by JavaScript.

And if you are using JavaScript, you may want to consider the noscript option, for users who have JavaScript disabled.

The Script

The following script will take a numeric input from a simple link parameter, and save it in a session.

However to make sure its numeric, we need to validate it first, this is done by the regexp "/^[\d]{1,2}$/D", the first part "[\d]" tells php that the content must be numeric value, the nest "{1,2}", dose so any value between 0-99 is considered valid.

<style type="text/css">
<?php
session_start();

if ((isset($_GET['StyleSheet'])) && (preg_match("/^[\d]{1,2}$/D", $_GET['StyleSheet']))) {
  $_SESSION['styl'] = $_GET['StyleSheet'];
} else {
  // Default StyleSheet
  $_SESSION['styl'] = '1';
}

echo '@import url("StyleSheet' . $_SESSION['styl'] . '.css");';
?>
</style>

The links used to shange the StyleSheet, works by the use of URL parameters, the StyleSheet Selector will use this parameter, to chose the relevant StyleSheet. Lets try by using relative paths first.

<a href="?StyleSheet=1">StyleSheet 1</a>
<a href="?StyleSheet=2">StyleSheet 2</a>

And by using the absolute paths.

<a href="http://www.brugbart.com/?StyleSheet=1">StyleSheet 1</a>
<a href="http://www.brugbart.com/?StyleSheet=2">StyleSheet 2</a>

The PHP StyleSheet Selector works by using the number given in the URL parameter, as the last part of the filename, it then remembers the setting in a session variable, for as long as the user is active.

Post comment

Links that you insert are not nofollowed, but will be removed by admins if they are considered spam.

[url=Absolute URL for page]TITLE[/url]

You should insert code boxes around code examples, which will be automatically syntax highlighted.

[code1 html|css|javascript|php|sql]Your Code Here[/code1]

You may want to read our Privacy Policy before submitting your comment.