Riccardo
Riccardo

Reputation: 2216

Safe to use dynamic HTML stylesheets using PHP?

ih ave read about the technique to allow dynamic HTML stylesheets using PHP's preprocessor, however I was windering how safe this tecnique is, and if for any reason it is discouraged.

For example, instead of using typical:

 <link rel="stylesheet" type="text/css" href="http:mysite.com/style.css/>

I could use:

 <link rel="stylesheet" type="text/css" href="http:mysite.com/style.php/>

What do you think?

Upvotes: 1

Views: 231

Answers (6)

mellowsoon
mellowsoon

Reputation: 23241

As others have mentioned, PHP can be used to output any kind of text. So it's not a problem to output dynamic CSS (or even dynamic JavaScript). Be aware though that you're increasing your server load by doing this. The server will have to fire up the PHP engine to serve what would otherwise be a simple static .css file.

Upvotes: 1

Gumbo
Gumbo

Reputation: 655239

Yes, you can use PHP to generate your stylesheet. Make sure to declare the output properly as CSS by sending an appropriate Content-Type value specifying both the media type and the character encoding.

But note that it costs additional time and resources to generate the stylesheet with every request. So you should add some kind of caching mechanism (static files and HTTP caching) to reduce server load and even unnecessary requests.

Upvotes: 1

tplaner
tplaner

Reputation: 8461

If you can use .htaccess files you can set it up to parse *.css files as PHP using:

AddHandler application/x-httpd-php .css

Then you can use PHP directly within your *.css files.

Be sure to also set the header type to text/css as the others have mentioned as well:

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

Upvotes: 3

Hannes
Hannes

Reputation: 8237

You can render any kind of Text Output with PHP (and other stuff) including CSS, just make sure the right header is given header('Content-Type: text/css; charset=iso-8859-1'); (or any other charset).

But to be honest I can't think of an Situation were it would be necessary to use a dynamic stylesheet in that manner.

Upvotes: 0

Andrew Sledge
Andrew Sledge

Reputation: 10351

It's only as safe as the code that you put into style.php.

Upvotes: 2

Mikee
Mikee

Reputation: 2563

It's perfectly fine.

I'd suggest setting the following header in the PHP though:

Header("Content-Type: text/css");

Upvotes: 5

Related Questions