I would like to add a feature onto my site that would allow a user to choose between multiple styles. I am quite new to PHP but I'm guessing it would be able to be done. I've seen this feature on other sites. How would I go about doing this or could somebody refer me to a tutorial or guide on how this can be done? Thank you.
To start you off, you could simply make the stylesheet link(s) dynamic:
<link rel="stylesheet" href="<?=$style?>" type="text/css"/>
And provide links that change them:
<a href="/page.php?theme=racecar">Racecar</a>
On the server, assign $style
according to the query string, it would also be a good idea to default to something in case the user decides to modify the URL:
<?php
$stylesArr = array('racecar', 'magenta', 'cartman');
if(isset($_GET['theme']) && in_array($_GET['theme'], $stylesArr)) {
$style = $_GET['theme'] . '.css';
setcookie("theme", $style, time()+(3600*24*30));//expires in one month
} else {
if(isset($_COOKIE['theme']) && in_array($_COOKIE['theme'], $stylesArr)) {
$style = $_COOKIE['theme'] . '.css';
} else {
$style = 'default.css';
}
}
?>
<link rel="stylesheet" href="<?=$style?>" type="text/css"/>
You can propogate the user's style via the query string, cookies or sessions.
You can store information about style in cookies, or in database if users are regitered. And then depending on value add required css file on page with php.
Depending on how your pages are rendered it might be best to store the theme in a cookie once a theme has been selected otherwise you need to append ?theme=racecar
to every link on your page.
if(isset($_GET['theme']))
{
setcookie('theme', $_GET['theme']);
$style = $_GET['theme'];
}
else if(isset($_COOKIE['theme']))
{
$style = $_COOKIE['theme'];
}
else
{
$style = 'default';
}
<link href="/styles/<?php echo $style; ?>.css" rel="stylesheet">
I've also seen it done with javascript.
Same basic idea as a few other answers: you write the chosen style to a cookie, and then read that when the page loads to determine which stylesheet to load.
With javascript, you have the added benefit of being able to switch styles without reloading the page, and if you set up your css nicely, you can switch something like the body's id or class and have a new style without having to download a new stylesheet, so the style-switch happens almost instantly.
Very sweet effect, good luck with the implementation.