CSS and PHP: Switching Themes
A couple of years ago I was asked to provide a very interesting feature to a mobile website. What I was asked to do was create in interface that would allow users to create their own themes. The catch was that it wasn’t just about loading different stylesheets, it was about each user having complete control over the look and feel his/her area on the site. This meant that I had to consider quite a few interesting questions.
How could I make a css file dynamic?
Would I use a database to store the theme information?
Was this even possible?
After some intensive thought I finally found the solution. In the two years that have passed since then I have thought a bit more on this topic, and the simplest and fastest version of this system will be discussed here.
How it works
The way this system works is very simple. In essence, any site that has registered users or members will assign something unique to identify that user. Usually this is a username or an email address, and almost always a database user ID is assigned to a user. Thus you have a distinct way of identifying a user that has logged into your site, right?
So now we have a way of identifying a user – let’s say by the username. So we can say that when a user – let’s call him “John” comes to the site, we can load the “John” css stylesheet. The “John” stylesheet will have the user- specific information in it, and we will assume for these purposes that the stylesheet is called john.css, and that john.css resides in the ‘/css’ directory.
Now let us for simplicitiy just assume that the username of every logged in user is carried through the url, in the form of:
so, we can then tell our script to look for the stylesheet if the user is logged in by saying something like:
$cssFile = $_GET[‘username’];
$cssFile = ‘default’;
$cssFile = ‘default’;
What will happen now is that if the username is set, the script will check if a stylesheet relative to that username exists, and if it exists we assign it to the variable $cssFile. If the username is not set or the file relative to the username does not exist – if /css/john.css does not exist – then the $cssFile variable will be assigned a value of ‘default’, meaning it will load the default stylesheet. Note that you might be getting the stylesheet name from a database, or a session variable, a cookie or a post value – it does not really matter.