PHP CSS Theme Switcher with Cookies

Although i wrote this a while ago, figured id put it up to start my blog posts and test out how well google actually indexs’ these pages. It was also the first script i officially developed myself =)

Also it was rather relevant article to put up, due to there being absolutly no prewritten php scripts for this concept. I suppose most people are quite happy to do something like this in javascript (which is alot easier). But id figured to try and achieve this with php, for the simple reason of it being server side.

replace the first three variable names with the name of the style sheet you have available, ive used business, modern, web2 here as examples. you will need to have the style sheets uploaded on the same directory.

It is critical that this first section goes before the html <head> tag, and that there are no white spaces infront of the <?php tag, otherwise the browser will parse the white space, and the header will be already sent for the page, and not allow ’setcookie’ to work.

before doctype

<?php
$theme1 = business;
$theme2 = modern;
$theme3 = web2;
if(isset($_POST['style']))
{setcookie('style', $_POST['style'], time()+(60*60*24*1000));
$style=$_POST['style'];}
elseif(isset($_COOKIE['style']))
{$style=$_COOKIE['style'];}
else
{$style=$theme1;} ?>

head

<head>
<link href="<?PHP echo $style; ?>.css" rel="stylesheet" type="text/css" />
</head>

body

<body>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post"> 
<select name="style"> <option <?php echo "value='$theme1'";
if($style == $theme1)
{
echo "selected='selected'";
}
?>><?php echo $theme1; ?></option>
<option <?php
echo "value='$theme2'";
if($style == $theme2)
{
echo "selected='selected'";
}
?>><?php echo $theme2; ?></option>
<option <?php
echo "value='$theme3'";
if($style == $theme3)
{
echo "selected='selected'";
}
?>><?php echo $theme3; ?></option>
</select><input type="submit" />
</form>
</body>

This switcher, will remember the option you have chosen with cookies (change this to a session if you would like), remember your selection in the drop down, and update the style sheet on first page load (a cookie wont take effect until the 2nd page load, since it is being set on the first page, so the selection was captured through the forms method variable).

Example here - (NB no style sheets uploaded, but you can view source to understand what i mean)

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

Image CAPTCHA
Enter the characters (without spaces) shown in the image.