A PHP Css stylesheet switcher
This is an English translation of the original tutorial.
———————-
Following my previous article, I keep on publishing the “secrets” behind Jek2k.com.
Today we’ll see how to create a Css stylesheet switcher using PHP, to change your Css on-the-fly.
There are many techniques to do that.
First, using Javascript.
On A List Apart you can find a very well written tutorial to create a Css switcher with JS, using a cookie to keep the user’s preference.
And the obtained page also conforms to W3C standards.
The main problem of this method is that, being Javascript, it runs on the client, so it depends on the browser and requires the user to have JS enabled.
The validity of this technique depends on your site’s target. No problem if you have a tech-savvy users target, with modern browsers and smart enough to not disable Javascript!
I chose to use another method, using PHP, not because of my users, but because I use WordPress, which is written in PHP.
Aside from this, PHP runs on the server, so it is browser-independent.
A List Apart has a very good tutorial which covers this method too.
A very easy, step-by-step tutorial.
I’d add just a couple of suggestions, to make it even smoother.
First:
the cookie duration.
Do you really want to keep the cookie for a year??!!? I think it is really too long.
So, in the following piece of code
<?php
setcookie ('sitestyle', $set, time()+31536000, '/', 'yourdomain.com', '0');
header("Location: $HTTP_REFERER");
?>
change the value 31536000 (duration of the cookie, in seconds).
to 2592000 to set a monthly cookie, or 604800 to set a weekly one
Second:
the code that reads the cookie. Change the following
<?php echo (!$sitestyle)?'defaultstyle':$sitestyle ?>
to
<?php echo (!$_COOKIE['sitestyle'])?'defaultstyle':$_COOKIE['sitestyle'] ?>
which seems to work better (at least, it does work better for me).
Well, that’s all folks!
I hope this can be useful to someone.
This tutorial is provided as is. Please do not email me questions or support requests about the scripts contained in this page. Use the comments below instead. Thank you.
About this entry
You’re currently reading “A PHP Css stylesheet switcher,” an entry on jek2kdotcom
- Posted on:
- 01.08.2006 @ 2am
- Categories:
- PHP, Tutorials, Web Development
11 Comments | View
Come on, leave your feedback!