View Full Version : how should I handle a dynamic .css file?

01-02-2006, 11:47 PM

here is the idea, I would like to have different styles available for a website. The different styles would be stored in a database. Here is the html line including the .css file:

<link rel="stylesheet" type="text/css" href="/css/styles.css" media="screen, projection" />

The style will be passed through the querystring (&style=). The css file should then contain php code. Problem, it can't.

How do you handle this? What would be the best approach according to you?

01-03-2006, 12:00 AM
Either change the link to a.php, or config the server to treat .css as a php file (the former is 'better').
<link rel="stylesheet" type="text/css" href="/css/styles.php" media="screen, projection" />
Then something like:

echo '#body {color:#fff;font-size:12pt;}';

etc. (driven by your db or whatever);

01-03-2006, 12:02 AM
What about MIME type? isn't the .css extension to be here for a purpose? If not, why not just name regular stylesheets with a .txt extension?


01-03-2006, 12:10 AM
You can set the PHP to output whatever header you like.

01-03-2006, 12:40 AM
You can set the PHP to output whatever header you like.
great post... what does that mean?

Velox Letum
01-03-2006, 01:05 AM
No need to be sarcastic.

What it means is PHP can masquerade as anything you want. CSS, images, XML, anything. A header is what tells the receiving party exactly what it is, so it knows what to do with it. Example:


// Define header
header('Content-type: text/css');

// Generate CSS
$css = 'body {' . "\n";
$css .= ' margin: 0px;' . "\n";
$css .= ' padding: 0px;' . "\n";
$css .= ' width: 100%;' . "\n";
$css .= ' min-width: 800px;' . "\n";
$css .= ' min-height: 600px;' . "\n";
$css .= '}';

// Output CSS
echo $css;

This code would be viewed as a stylesheet due to the header up top. All you'd have to do is upload the file and define it as your stylesheet. You can get even more pretty if you want and name it styles.css and use a .htaccess file entry to make it parse as PHP. Just generate it from the db or whatever you need.

01-04-2006, 09:39 PM
Thank you very much for this clear, concise and complete explanation :)