On occasion, it is easier to produce CSS dynamically with a language like PHP than to keep styles in a static file. Reasons for doing so might include a desire to automatically generate CSS3 prefixes to simplify the CSS code, or customizing our site styles in response to the date or season.
We can't use PHP in any file that does not have a .php extension… so how to we tell our stylesheet that it is, in fact, PHP? By doing something that may appear a little counter-intuitive: linking our pages to a PHP page as a stylesheet.
<link rel="stylesheet" href="styles.php">
When we do this, we have to take two other steps. The first is to convince styles.php that (in regards to other pages) it is not PHP, but CSS.
A PHP function that I’ve looked at in the past is header()
. Previously, I used it to redirect a link; now, we are going to use it to fool the browser into believing that styles.php is actually a CSS file. As the very first line in styles.php, write:
<?php header(‘Content-type: text/css’); ?>
That’s step number one. The browser will now take any CSS we provide on that page, including any CSS that is generated by PHP, as if it were real style declarations. For example, as the next line in styles.php you could write:
<?php echo "* { border: none; }"; ?>
It’s important to remember that we can do all the scripting we like on this page, but the final output that the browser sees must be CSS… ideally, valid CSS. Obviously, this partial CSS reset is only a simple example: we'd use the PHP abilities of our stylesheet for far more practical needs, such as the scenarios given above.
The final step may be necessary depending on your hosting provider: you also need to tell the server to deliver styles.php as a stylesheet. In the .htaccess file for your site, add the following: AddHandler application/x-httpd-php .css
That's it. We can now go ahead and use any PHP we wish to dynamically generate CSS code in our stylesheet. There are just two downsides:
- As a PHP file, the stylesheet must now be generated every time it is called, meaning that the file cannot be cached by the browser.
- This generative call results in a small server hit for every visitor.
The two effects combine to fractionally slow down page load time: not a significant effect on small, low-traffic websites, but a factor to keep in mind as site traffic increases.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.