Dynamic CSS using cookies in a stylesheet.

This technique is interesting for a lot of values to modify.
For a few values, a method similar to the one described for cookies in a page should be better.

The HTML and PHP

In each page we import the CSS/PHP file fixe3col.php.

<style type="text/css">
@import "fixe3col.php";
</style>

We write a file switcher.php which will allow us to set the style value in a cookie and redirect to the calling page using variables.

<?php
if(isset($_GET["style"])){$style_cookie=$_GET["style"];}
if(isset($_GET["page"])){$page=$_GET["page"];}
setcookie('style',$style_cookie,time()+3600,'/',"domain",'0');
/*here $domain="css.tests.free.fr";*/
header("Location:$page");
?>

For the style 1, The link that will allow the style switching will be:

<a href="switcher.php?style=1&amp;page=nameofpage.php">style 1</a>

The CSS/PHP file

We set all the default values -here for the text and background of body- and the values to set according to the style found in the cookie.

<?php
header("Content-type: text/css; charset=iso-8859-1");
header("Cache-Control: must-revalidate");
$ExpStr = "Expires: " .
gmdate("D, d M Y H:i:s",
time()) . " GMT";
header($ExpStr);
/*valeurs par défaut*/
$textcolor="#0A00B0";
$backgroundcolor="#E9F5FE";
if(isset($_COOKIE["style"]))
{
switch ($_COOKIE["style"])
   {
   case "1" : $textcolor="#FDC990";
              $backgroundcolor="#908E53";
              break;
   case "2" : $textcolor="#908E53";
              $backgroundcolor="#FDC990";
              break;
/*etc*/
   }
?>
body{
color:<?php echo $textcolor?>;
background-color:<?php echo $backgroundcolor?>;
}
/*etc*/

The stylesheet built according to the cookie style will be sent to the browser which will apply the styles as it does for this page.

The scripts have been simplified and must also consider what may happen.

If the visitor has blocked cookies, the default style will be applied.

This page doesn't use any hack for the layout or menu.
Conditional comments have been added for MSIE.

Espelette pepper
Change style
with cookies
basic style 1 style 2 style 3
with variables
style 1 style 2 style 3

Back to the example page.