How to Pass Php Variables Into Your CSS File.

October 19th, 2010

The most obvious question you have to ask yourself when attempting this task is “Do I really need to do this?”.  If you have made up your mind to do this I will present you with your options.


1) Include you css file with php – This requires that you add the script tags into your code and, when viewing source, you now have to see this css when you view source.  This may effect your ability to debug as line # errors no longer line up to your editor.

  <title>Justin Campo</title>
  <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"/>
  <?php include("site.ss"); ?>

2) Setup your server to parse php in your css files. On a linux box this is most commonly done in your .htaccess

AddType application/x-httpd-php5 .html .htm .css

if you are only doing this on one page use

<Files yourpage.html>
AddType application/x-httpd-php5 .html .css
</Files>

but if you want the entire server to do it you can edit your httpd.conf. If you do any of these you are going to need to declare the header for all css files effected.

<?php Header ("Content-type: text/css");?>

3) Parse / Cache – This is a rather complex method but it is worth working with if you plan on using the system on a large scale or professional setting. I recommend this reading.

4) Mod Rewrite – Basically you no longer make css files, they just look like css files from the front end. Site.css would really be Site.css.php, this is done via .htaccess file.

RewriteEngine On
RewriteRule ^site\.css$ site.css.php

It is a rare case when you can’t make do with dynamically swapping class/id names, or handling changes with javascript. If you have to these are the ways. I end with this article about how bad it is to use variables.

Leave a Reply

Name
Mail (will not be published)
Website
Comments