This page uses CSS and javascript. If you can see this message, CSS (or javascript) is not enabled in your browser options.
The page will not appear as intended.
This page does not exist in the other version of the site.

Dynamic CSS via PHP: using cookies to switch style

PHP can generate a stylesheet and can also modify the settings in the css rules in the style section according to the user's preferences.
This page will set cookies to store the colors selected by the visitor for a minute and will use them in another page.


Your browser may not be able to display a style sheet generated by PHP.

As you have no cookie, the text is in black on a white background.

text

Choosing a color

The text
black white dark blue light blue red yellow
The background
black white dark blue light blue red yellow

After having made a selection and clicked on "select" you can test it during a minute.

The code

Setting cookies

Any method can be used.
For this page, it is a form, but variables in the URL, a session variable or a MySQL request can do the same.

We need two variables : $couleurtexte, $couleurfond.
The following script will install cookies with the selected values. They will expire 60 seconds later.

/*Use $_POST instead of $_REQUEST for a form*/
if(isset($_REQUEST['couleurtexte']))
{
setcookie ('couleurtexte', $couleurtexte, time()+60, '/', 'mon_domaine.com', '0');
setcookie ('couleurfond', $couleurfond, time()+60, '/', 'mon_domaine.com', '0');
}
else
{$couleurtexte="#000000"; $couleurfond="#FFFFFF";}

Getting the values

At the beginning of any page, we extract the values.

if(isset($_COOKIE["couleurtexte"]))
{$couleurtexte=$_COOKIE["couleurtexte"]; $couleurfond=$_COOKIE["couleurfond"];}
else
{$couleurtexte="#000000"; $couleurfond="#FFFFFF";}

Setting the values to CSS rules

Here, we modify div.test with PHP.

<style type="text/css">
<!--
/*<![CDATA[*/
#content div.test{
color:<?php echo $couleurtexte;?>;
background-color:<?php echo $couleurfond;?>;
}
/*]]>*/
-->
</style>

As long as the cookies are found, the style will be the user's choice. If the cookies expired or were deleted, the user will find the default values.

Examples of pages using dynamic CSS with variables, cookies or a session are in the site about CSS.

Valid CSS! Valid XHTML 1.0!
tableless pages