Show Me A Working Example of Dynamic CSS using PHP »

PHP in CSS Files – Dynamic CSS Using PHP Stylesheets

It all started when I needed to use PHP in a website that was originally basic HTML files. The site contained at least 30 pages, and I was dreading having to rename every HTML file PHP and updating all the links, just to enable me to include a couple of humble lines of PHP. Instead, I used apaches’ .htaccess file to override the server settings, making it treat the htm and html files with the PHP processor, which you can do by adding the following lines to .htaccess (or if you don’t have one, by placing a file of this name into your web root folder containing:)

AddType application/x-httpd-php .html .htm
AddHandler application/x-httpd-php .html .htm

NOTE : This will only work if these overrides are allowed for this folder (use ‘AllowOverride all‘ in this folders entry in Apaches’ httpd.conf file. If you pay for a hosting account this may or may not work (some may not allow this directive to be overridden with .htaccess). If you get ‘Internal Server Error 500‘, this is probably the case! Check your error logs!)

Then, I wondered … could I use PHP with my CSS style sheet? I tried:

AddType application/x-httpd-php .html .htm .css
AddHandler application/x-httpd-php .html .htm .css

And sure enough, I was able to use PHP in the css stylesheet, and it behaved exactly as it should. I began with the following block of code:

body {

<?php echo "background-color:black;"; ?>

And after knocking together a simple html document that included our PHP CSS stylesheet, I was looking at a web page with a black background!

Imagine The Possibilities!

While this is a painfully simple example, the possibilities are endless! By turning the PHP processor on my CSS Stylesheet – in theory – I have the freedom to write a web page that has the same stylesheet for everyone, yet allows each individual visitor to see a completely different design, allowing each visitor to customise the colour of the links, text, or formatting and layout of the page they see. My first thoughts were you could use cookies to get and set the various viewing options, and generate the CSS Stylesheet on the fly for each visitor with code like:

body { font-family:<?=$_COOKIE['roger_davies_font_face'];?> }

p { color:<?php
          switch ($_COOKIE['roger_davies_text_colour']) {
             case 1 : echo "white;";
             case 2 : echo "black;";
             case 3 : echo "purple;";
             }    ?>

a { color:<?php
          switch ($_COOKIE['roger_davies_link_colour']) {
             case 1 : echo "red";
             case 2 : echo "green";
             case 3 : echo "blue;
             break;   } ?>
#container { width:<?php echo $_COOKIE['roger_davies_screen_width']; ?>  }

I’m sure there are more exciting applications, but I was just excited that it worked at all!