Why simply use PHP variables for dynamic stylesheets? - php

I've been reading about dynamic stylesheets and have stumbled across several options, including sass, and less. But my question is why not just turn my stylesheet.css into stylesheet.css.php and simply use php variables. Then, I avoid all the dependency issues associated with all these other approaches.
Am I overlooking some serious problems by doing it this way?

There is the argument of code re-use: when writing PHP code to generate CSS, you're effectively duplicating (some) of the logic behind things such as sass and less. Why would you do that when there's a widely-used, tested and complete alternative available?
Another thing is performance. Standard CSS files are served by your web server with sane headers regarding caching by the browser. Your browser will not download that same CSS file each time, it just gets it from the browser-side buffer. By default, PHP is not cached at all (and you usually wouldn't want it to be). This means that, by default, your PHP-generated CSS would not be cached, incurring extra load on your server and extra waiting time for your client. While some of this can be solved (including sane header output in the PHP code that generates your CSS), some of it cannot (the overhead of the web server starting up PHP, for example).

Am I overlooking some serious problems by doing it this way?
I host all static assets on a CDN, which you should too. CDNs don't do PHP.
Also: caching, runtime performance, minification

PHP variables used in inline CSS code
Using PHP variables in CSS has many advantages, one of them is that you don't have to learn a new syntax. The use of PHP variables in CSS code is a known practice already implemented in many frameworks, themes, and other website-related scripts.
The most common use is in inline CSS. Here is an example of inline CSS making use of PHP variables:
<html>
<head>
<style>
.class {
color: <?php echo $text_color; ?>
}
</style>
</head>
<body>
</body>
</html>
This technique is usually used when the PHP variable represents a user setting set via an admin interface. One practical example would be in a WordPress Theme where the user can set the background or text color via the theme's backend.
PHP variables in an external CSS file
When it comes to external CSS files, it is also possible to use PHP variables, but in order to avoid PHP from parsing your CSS file each time it is retrieved, you would have to save the output to a static file like stylesheet-processed.css.
Both SASS and LESS need to be parsed before being saved to a ".css" file. The same goes for your PHP file, which you would execute and save the output to a static ".css" file, just like the other syntax.
Parsing CSS files is a very common practice and is widely used on many websites, and most well known websites. It is usually done to increase site's performance by minifying (~25% saving) the CSS code, combine multiples files into one (less HTTP requests), and gzip (~80% saving) the resulting files.
Here is an example of how you would use PHP variables in a file named stylesheet.php, and save the result to stylesheet.css:
<?php
// Get the parsed CSS code with the
$processed_CSS = file_get_contents('http://www.example.com/stylesheet.php')
// Save the processed CSS to a static CSS file
file_put_contents('stylesheet.css', $processed_CSS);
Put the above PHP code into a file named "parse-css.php" and access it through your web browser in order to create or update the resulting static CSS file.
And then in your HTML code you would include stylesheet.css instead of stylesheet.php.
You could improve your parser to make it minify the CSS code too, for example using the CSSMin PHP class.

Related

How to create dynamic external javascript files?

I am thinking about how some online services create dynamic JavaScript files. These files have the .js extension, but their content is not static. I found a sample file here. It seems that this script is generated with a higher level programming language. I think it is done with PHP or something similar, but I am not sure, and I have not found any documentation about this topic.
Is there any well known way to create these kind of dynamic JavaScript files?
Consider carefully whether generating a dynamic JS file is necessary at all. Instead of generating dynamic JS, you can often simply inject static script(s) and use separate JSON to support dynamic configuration into your page.
If you view source on this (or about any) StackOverflow page you'll see that they're using this same pattern: Static external .js files that reference a separate centralized chunk of JSON for configuration. That JSON is what provides dynamism.
View source and look for this:
StackExchange.init({...
Most server side languages make it trivial to serialize an object to JSON so you can inject it into your page.
Here's ten reasons utilizing external static js files is preferable:
Cached
Code colored
Syntax checked
Separation of concerns
Reusable
Easier to read.
One less layer of abstraction
Can serve minified and obfuscated
Avoids string parsing on every request
StackOverflow and all the cool kids are doing it (hey, I promised 10 reasons.)
More info here: http://www.bitnative.com/2013/10/06/javascript-configuration-object-pattern/
That depends on whether you want to generate files or return data. Generating files would be done with something like file_put_contents. Alternatively you could have a .js file in a folder with a .htaccess file that tells you to execute it as php, allowing you to simply generate the script on the fly based on session, get, or post parameters.
You can use any server-side language to create dynamic javascript files, javascript files don't need to end with .js. If you really want your files to end with .js you'll need to edit your server settings to also process .js files as for instance PHP files.
You can also use server code to generate inline javascript.
But be careful when generating javascript files, it can become very complex when you are mixing two programming languages

SASS and/or LESS - can I create dynamic CSS files on the fly?

I'm using CakePHP to build my site (if that matters). I have a TON of elements/modules each having their own file and fairly complicated CSS (in some cases).
Currently the CSS is in a massive single CSS file, but for sanity sake (and the below mentioned details), I would like to be able to keep the CSS in it's own respective file - ie css/modules/rotator.css. But with normal CSS, that would call a TON of CSS files.
So, I started looking into SASS or LESS per recommendation. But - it seems these are supposed to be compiled then uploaded. But in my case, each page is editable via the CMS, so a page might have 10 modules one minute, then after a CMS change it could have 20 or 5...etc. And I don't want to have to compile the CSS for every module if it's not going to use it.
Is there a way I can have a ton of CSS files that all compile on the fly?
Side note: I'd also like to allow the user to edit their own CSS for a page and/or module, which would then load after the default CSSs. Is this possible with SASS and/or LESS?
I don't need a complete walkthrough (though that would be awesome), but so far my searches have returned either things that are over my head related to Ruby on Rails (never used) or generic tutorials on each respective CSS language.
Any other recommendations welcome. I'm a complete SASS/LESS noob.
Clarified question:
How do I dynamically (server-side) combine multiple CSS files using LESS? (even a link to a resource that would get me on the right track is plenty!)
If you want to reduce the number of CSS files & you have one huge css file that has all the component css, just link to it on all pages & make sure you set cache headers properly.
They will load the file once and use it everywhere. The one pitfall is initial pageload time; if that's not an issue go with this solution. If it is an issue consider breaking down your compiled CSS files to a few main chunks (default.css, authoring.css, components.css eg.).
Don't bother trying to make a custom css for each collection of components, you will actually be shooting yourself in the foot by forcing users to re-download the same CSS reorganized in different ways.
Check out lessphp (http://leafo.net/lessphp/). It's a php implementation of less and can recompile changed files by comparing the timestamp.
Assuming that 'on the fly' means 'on pageload', that would likely be even slower than sending multiple files. What I would recommend is recompiling the stylesheets whenever a module is saved.
The issue of requiring only necessary modules should be solved by means of CMS. It has nothing to do with SASS or LESS.
If your CMS is aware of which modules current page has, do not run a SASS/LESS compilation (it will be painfully slow unless you implement caching which is not a trivial task). Instead, adjust your CMS's logic so that it includes each module's CSS file.
Advanced CMSs like Drupal not only automatically fetch only necessary CSS files, but also assemble them into a single file and compress it.
And if your CSS is not aware of which modules current page has (e. g. "modules" are simply HTML code that is saved into post body), then you can't really do anything.
UPD: As sequoia mcdowell says in his answer, making users download one large CSS file once is better than making them download a number of lesser CSS files that contain duplicate code. The cumulative size of all those smaller CSS files will turn out to be larger than the size of a full CSS file.

What are the benefits of using .css over .php with content-type: text/css?

What are the benefits of using a CSS external stylesheet over a php file set to content-type: text/css? If you place this header at the top of a PHP file I feel like you have so much more potential:
<?php
header("Content-type: text/css");
if($query_string = "contact_us") {
#nav {}
}
?>
(^ that's a .php file). http://shapeshed.com/using_php_to_enhance_css/
If there are no downfalls (and I checked how they were cached in Chrome's Network Panel and I believe it's the same), isn't it kind of like whether to use .html or .php?
Thanks for any feedback.
Here are some differences:
PHP will create extra CPU / memory overhead compared with serving purely static CSS. Probably not all that much, but still a consideration. The more processing you do the bigger a deal it is, obviously.
You can't push PHP files to a CDN
SASS and LESS have been developed to deal with any dynamic features you might need so PHP isn't likely necessary
Sounds like you're worried about serving more CSS than is needed for certain pages. Realistically it's not an issue since browsers will cache the CSS after the first download.
Additional thoughts:
I wrote a UI template engine that isolates both JS and CSS code to only the specific views on which they are used. If a CSS or JS is used more than once, it is pushed to the "kitchen sink level" and included globally. This limits selector conflicts and also best balances the number of HTTP requests and total download size per request. Also keeping relevant code (i.e. button event listeners or page / element-specific styles) close together helps with more rapid programming, especially for non-expert teams / developers.
That could have been nice before CSS preprocessors such as SASS or LESS.
Dynamic CSS isn't even as useful as dynamic JavaScript, much less dynamic HTML. Having one large file with all the rules in it is more effective than having a file with rules that change since you can more easily cache the former in the client than the latter.
The reality is that there isn't much benefit to this...dynamic CSS doesn't have many valid use-cases, and the one you're describing certainly isn't one of them. If you just combine and minify all of your css into a single file, it'll cache on the client and be downloaded only when you bust the cache it.
In a modular CMS, this could be useful. As long as your application could generate a .php URL that consistently generates the exact same CSS for caching purposes, you could dramatically reduce the amount of CSS to download. For example, pages that uses 1 theme and 5 modules (each providing CSS) could return the CSS for that combination, instead of the CSS for 1 theme and 50 modules. That could be the difference between 50KB of CSS and 500KB -- a huge savings for slower connections.
If your website is hand-made, as in a website that has specific goals known ahead of time, then there's really not a good reason to do this as others have answered.

include or call php or html file via .js

I have a js file that has the code for navigation for a site with ~600 pages..
Now I want to change the menu(colors, background, links etc) and I don't want to edit the JS file as the code here is like using images for the menu..so I was thinking that I will create a php file or html file and then call it inside that js file. Is this something possible?
Please advise.
You could have the js render an iframe instead of an img and pass along the url to the php/html.
You need to understand the difference between PHP, HTML and JS. They each occupy a different domain in web programming. PHP is for server side logic, HTML is a structural language and JS is an action-oriented language intended to function on top of the HTML that exists in the page (and may be rendered in JS).
All programmers have at one point tried to "hack" code like you are doing, by trying to find a band-aid fix to a complicated solution. It is not worth it. You will lose performance in the best of cases and either fail outright or lose browser compatibility and user interface quality the vast majority of the time.
In short, take your time and edit the JS. You can always do a find/replace on images to strip them out and insert CSS class declarations in their place. Do it right and you'll save yourself a big headache later on.

CSS Preprocessor or PHP?

If I'm writing code in PHP is there a reason why I would use a CSS Preprocessor instead of PHP? For example, I could use PHP in my CSS file by having this in my header:
<link rel="stylesheet" type="text/css" media="all" href="style.php" />
That way I could pass it variables like style.php?color=#000
Or I could use something like LESS to preprocess my CSS. If I use less.js, I'm not sure how I would be able to pass variables like in the previous example.
Now, I've heard that PHP CSS files can't be cached so I can see why that would be a problem, especially if the CSS file was large. But I'd like the ability to pass variables to my CSS sheet.
Can someone tell me a little more about why I'd use one over the other, and/or how I would pass variables to my .less file if I used less.js?
Now, I've heard that PHP CSS files can't be cached so I can see why that would be a problem, especially if the CSS file was large.
PHP CSS files can be cached, but if you pass dynamic values to them, the point of caching is usually lost. If you have a dynamic value that may change with every request, caching becomes pointless.
Also, shoving huge amounts of mostly static CSS through the PHP preprocessor tends to be a waste of server resources.
The much easier approach is usually to have static CSS files, and to declare all dynamic values in the page body:
<!-- the static style sheet declares all the static values -->
<link rel="stylesheet" type="text/css" href="static.css">
<!-- now you override all the dynamic values -->
<style>
.classname { color: <?php echo $color; ?> }
</style>
This way, you can have dynamic values as you please, but you still avoid having a lot of CSS data being processed by PHP.
Any and all HTTP requests CAN be cached, you just generate appropriate cache headers see rfc2616.
Interestingly, caching will work very nicely because if your GET values change then you DON'T want the PHP to be cached anyhow. So go ahead and enjoy using them.
Part of your css should be something like:
<?php
header("Content-type: text/css");
?>
Here is a very interesting tutorial on it: http://css-tricks.com/snippets/php/intelligent-php-cache-control/
Beside browser caching, static files are much better for server-side caching:
Static CSS files can be cached into memory (and even precompressed with some servers like nginx) which enables you to serve them from cookie-less static-serving domain. Using a web server like nginx can create a huge performance boost since less RAM is used. If you don't have much RAM or have a lot of traffic, the difference can be enormous.
If you have a small website than it does not matter much.

Categories