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 an 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 of their 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 time that has 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. 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. 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 styles in it, and we will assume for these purposes that the stylesheet is called john.css, and that it resides in the /css directory.
Now, let us for simplicity just assume that the username of every logged-in user is carried through the URL in the form of:
index.php?username=john
So, we can then tell our script to look for the stylesheet if the user is logged in by saying something like:
if (!empty($_GET['username'])) {
if (file_exists('css/' . $_GET['username'] . '.css')) {
$cssFile = $_GET['username'];
} else {
$cssFile = 'default';
}
} else {
$cssFile = 'default';
}
What will happen now is that if the username parameter 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 query, a session variable, a cookie, or a POST value—it does not really matter. The underlying logic remains the same: a dynamically assigned stylesheet name that matches the active user’s preferences.
