By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

PHP StyleSheet Selector

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

Edited: 2012-08-25 04:39

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">

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");';

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="">StyleSheet 1</a>
<a href="">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.