With a bit of planning, you can make your site very dynamic, very easily. Using rich, definitive XHTML tags gives an extreme amount of versitility with CSS. What we’ll be doing here is using php to allow the user to pick which style they would like to see. Similar to the likes of most phpBB forums, or Last.fm.
To start, create two stylesheets. That’s not too difficult, is it? Name them black.css and red.css. After we do this, we’ll create a php file that sets a cookie, and displays the stylesheets. To make things easy to grasp, we’ll start out with an empty if() statement.
1
2
3
4
5
6
| <?php
$style = $_GET['style'];
if(!isset($style)) {
}
?> |
On the first line, we set a variable for $style, and since it’s a $_GET variable, you’ll need to take further action in securing it. And then we set the if() statement, that basically says if $style is NOT set. Now we’ll follow up on that and add in some code within the if statement.
1
2
3
4
5
6
7
8
9
| <?php
$style = $_GET['style'];
if(!isset($style)) {
echo '[';
echo '<a href="'.$PHP_SELF.'?style=black">Paint it Black</a> | ';
echo '<a href="'.$PHP_SELF.'?style=red">See Red</a>';
echo ']';
}
?> |
output…
[Paint it Black | see Red]
So there we have our links ready. Take notice of how the parameters of ?style= are ‘black’, and ‘red’. That’s what we named our two stylesheets, remember? We need to keep that order. If they don’t match the filenames, we’ll run into trouble.
Now we’ll get to that cookie. Everyone likes cookies, yes? Of course. Include this follow snippet in with your last snippet:
1
2
3
4
5
6
| <?php
if (file_exists('/css/'.$style.'.css')) {
setcookie("styleswitch", $style, time()+(31*86400), '/');
header("Location: setstyle.<?php");
}
?> |
Beautiful. First we check to see if the stylesheet is actually there, and if it is, we create a cookie named ’styleswitch’, collect which style the user picked, and set the cookie to stay fresh for a month (31*86400=31days=1month).
Next we’ll actually execute the switch. You know how you include your <link rel=”stylesheet” code in the head tags? We’re going to do that, just a little differently.
1
2
3
4
5
6
7
| <?php
if(isset($_COOKIE['styleswitch']) && file_exists($_COOKIE['styleswitch'].".css")) {
echo '<link rel="stylesheet" href="/styles/'.$_COOKIE['styleswitch'].'.css" />';
} else {
echo '<link rel="stylesheet" href="/styles/default.css" />'';
}
?> |
First we check to see if the cookie has been set, then we make sure once more that the stylesheet is a real file. If eitehr of those fail, we revert to the default stylesheet, ‘default.css.’
Aside from a bit of configuration and optimization, you’re done
Also…
Don’t stop here. Look for more info regarding cookies, and securing $_GETs. If you have any questions, feel free to post them.
EDIT: I just fixed a few things within the coding. WP-Syntax seems to be eating some things… Or I just don’t know how to properly use it.