Using PHP to let the user switch to a different CSS file is nothing new. But it is one of the things that I am often asked about, so I thought it would be good to have a write-up to refer people to in the future.
As I mentioned this will work when JavaScript is disabled. It will not work when cookies are disabled, however. Nothing bad will happen, but it simply won’t work and the user will be returned to the same page they were on. Just to make you aware of that right from the start.
I use this style switcher to let visitors switch between two different layouts (“Zoom” and “Normal”) here on 456 Berea Street. If you want to let the user choose between more than two stylesheets you will need to come up with a different solution.
I wouldn’t call myself a PHP expert by any means, so if you think my code could be improved in any way, please let me know.
To switch styles, all you need to do is activate the link to the styleswitcher. As you may have noticed if you have tried that, the URL that invokes the styleswitcher is always the same: /styleswitch/. The link leads to a php file that looks like this:
- <?php
- $layout = (isset($_COOKIE['layout']) && ($_COOKIE['layout'] == "zoom")) ? "main" : "zoom";
- setcookie("layout", $layout, time()+31536000, '/');
- $ref = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "http://{$_SERVER['SERVER_NAME']}/";
- header("Location: $ref");
- ?>
- Line 2: If the layout cookie exists (the browser has been here before) and has the value “zoom” (the user has switched to Zoom layout), $layout is set to “main”. Otherwise $layout is set to “zoom” (the browser doesn’t accept cookies, the style switcher has not been used with this browser, or the user has switched to Normal layout). Note that “main” and “zoom” are the file names (except for the .css extension) used for the respective styles. Change these values to match your file names.
- Line 3: The value of $layout is stored in a cookie.
- Line 4: If a referer header exists, its value is stored in $ref. If it doesn’t exist, $ref is set to “http://{$_SERVER[‘SERVER_NAME’]}/” as a backup to redirect the browser to the home page.
- Line 5: The browser is redirected to the URL stored in $ref.
- <?php
- $layout = (isset($_COOKIE['layout']) && ($_COOKIE['layout'] == "zoom")) ? "zoom" : "main";
- ?>
Finally, when loading the main style sheet the value stored in $layout is inserted instead of the file name in the @import path:
- <style type="text/css" media="screen,projection">
- @import '/css/<?php echo $layout; ?>.css';
- </style>