Amanahumpa
Amanahumpa

Reputation: 55

CSS thru PHP Parser vs. PHP as CSS source

To have my project respond to certain contexts of content, I want my CSS files to respond respectively instead of setting up additional CSS files (adds to http requests) or parsing the CSS right inside the respective php script (imho: quite messy).

CSS thru PHP parser

Now I could tell the PHP parser via .htaccess to treat css files too.
Disadvantages would be: Overhead of processing several css files in my current project-structure OR breaking structure to activate parsing of CSS files just in one subdirectory.
Either way I simply could do it like so:

AddType application/x-httpd-php php php4 php3 css

... vs. PHP scripts as CSS ressource

Or I could link a php source in the page metadata as css source.
Possible disadvantages: May be some browsers won't accept files with different extensions as CSS ressource...?
Anyways...:

<link rel="stylesheet" type="text/css" href="/style/preprocessed.css.php" media="all">

What would you suggest?

Upvotes: 1

Views: 102

Answers (2)

Halcyon
Halcyon

Reputation: 57703

So long as the resource returns Content-Type: text/css browsers will accept it as CSS.

If you want to reduce HTTP traffic use a tool like YSlow too analyze your website. It gives good solid tips on how to optimize your HTTP traffic.

There are 2 relatively easy optimizations you can do:

  1. Enable gzip compression. This reduces the filesize and typically decreases load times.
  2. Set proper caching headers. CSS files are typically static, they don't change from one request to another. I personally like fingerprinting as a caching strategy for resource files like CSS and JavaScript.

There are advantages to letting PHP handle CSS generation but if you can let Apache server the files, all the better. If you do want to serve them with PHP look at the readfile function. It allows you to read and echo a file with very low overhead.


You use the word parsing. I don't think you actually mean parsing but something like serving.

Upvotes: 1

No Results Found
No Results Found

Reputation: 102834

<link rel="stylesheet" href="style.php"> should work fine in all browsers, but make sure to set the correct header in your PHP file:

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

I wouldn't go parsing CSS files as PHP, otherwise you could do some dangerous stuff:

/* bad.css */
<?php unlink('index.php'); ?>

...or whatever. That shouldn't be able to happen (and other people working on the project may not expect it).

Ideally, you just process all your CSS beforehand and link to a minimized, regular CSS file.

Upvotes: 1

Related Questions