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.
Related
Goal: minimizing the loading time of my website
I did lots of scans and speed tests.
They all indicate, there is lots of time spent uselessly, waiting for a HTTP response.
The time spent actually sending data is very small compared to that.
Screenshot of a 'speed test':
I started loading all the scripts and styles in PHP and just echoing them:
<!-- loading a style -->
<style><?php echo file_get_contents("style.css"); ?></style>
<!-- loading a script (similar) -->
<script type="text/javascript"><?php echo file_get_contents("script.js"); ?></script>
That does work, however, the images still slow things down a little. How do I use php to read them and echo them as a <img> tag?
(The mentioned website is https://www.finnmglas.com/)
Everyone seeking answers to this:
You should not echo back images with PHP into the main file:
It messes up the loading time (makes it way longer)
And it delays the first render of your website. Even if you have less requests, you will want to have a quick first render (users will notice the delay)
Echoing images from a separate PHP file and including a <img> tag pointing at that PHP should not be a problem ^^
Yes, you can add data instead url to src attribute:
<img src="data:image/jpg;base64,<? php echo base64_encode($data) ?>" />
but I recommend this for small images. Better way for more small images is use it as sprites: https://www.toptal.com/developers/css/sprite-generator/
and for css/javascript use some minify preprocessor: gulp gulp-clean-css gulp-uglify-es
I noticed the same kind of issue of wait and lag...
there are many factors, the location of the server, location of the visitor (in the picscreen case ; location of the server that did the test), routers between the internet provider, etc...
I discovered that using a CDN is way better, the browser will connect to the CDN that have many servers around the world, then cloudflare ask your server and cache the HTML, js, css, images, videos.... so that delivery to the end point becomes way more faster
you can try https://www.cloudflare.com/
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.
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.
I've been trying to wrap my head around a good way to do this, but so far have come up empty, and needed some guidance.
Basically, what I have at the moment is a style selector, which gives 10 pre defined styles for the site that a user can choose from. Most of them are grotesque, and are merely proof of concept.
This is controlled by PHP and mysql. When a user logs in, and slects a non-default style, it is added against their user record in the DB. The site then refreshes, and loads the selected style.
It works really well, but now I want to try and have some granular control. For example, I would like users to be able to pick their own header background colour, heading text colour, sub heading colour and some font sizes.
It is a fairly trivial thing, and if I can't find a way to implement it, then so be it.
My initial thought was to have a table that has columns for each customizable part of the size, e.g. font size, colours etc. In the table, would be a record for each user. They then use some interface to pick and choose what they want, and then add it to the table.
My issue, was then what to do with the values that I retrieve from the DB. I would have liked to insert them straight into a CSS file, but I don't think this is possible without some server configuration changes, that I couldnt get to work.
So does anyone have any suggestions on the best way to do this, if there is any way at all.
Regards
Eds
The most obvious option to me would be to build a PHP script that would generate the stylesheet on the fly. This would only get called if there is a record in the table for that specific user that holds all the user-specific styles.
So for example, between your <head></head> you could put:
<?php if($user_has_style): ?><link rel="stylesheet" href="user_style.php" /><? endif; ?>
This calls the user_style.php script and generates the stylesheet needed.
You will have to add the correct headers to the output of the PHP stylesheet, which are:
<?php header("Content-type: text/css"); ?>
This website might be of some use, if you choose this method: http://mou.me.uk/2008/08/03/generating-dynamic-stylesheets-on-the-fly-using-php/
You have several ways to do this.
You may specify CSS properties directly in the style attribute of HTML tags, but that can quickly become tedious as you might have to insert code in scattered areas in the middle of your content, making maintenance harder.
You can also put all style definitions between <style></style> tags inside the <head> section, which partly eliminates the disadvantage of mixing content with presentation.
Finally, it is also possible to produce CSS files with PHP using database informations. Rename your stylesheet something.php, then put this at the top of the file :
<?php header('content-type: text/css'); ?>
This tells PHP that the content it will generate needs to be sent as a CSS file, so that the user's browser knows that it's a stylesheet. All that's left to do is to correctly reference your "mutable" stylesheet in the PHP script that holds your HTML content :
<link href="../layout/css/something.php"
rel="stylesheet" type="text/css" media="all" />
This will allow you to use this kind of things in your "CSS" file :
body
{
background-color:
<?php echo $userstyle['color']; // Retrieved from database somewhere above ?>;
}
However, if you care about performance, the latter solution may need some improvement using the Cache-control header, to avoid reloading the CSS file whenever the user follows a link in your website.
You can put CSS into html file in two ways. You can either put the code in the header under <style> tag or you can put css on a specific item like <body style="background-image:url('file.png')">. Both ways you do not need css file that is separated from .html file :)
I'm in the process of optimizing CMS website's CSS usage and I decided it would be a good idea to serve the CSS through PHP so I could send the ID of the current page to the stylesheet, e.g:
<link href="/css/style.php?id=<?php echo $page_id; ?>" type="text/css" rel="stylesheet" />
I did this because I thought it would be a good way to stop CSS meant for different pages being loaded on pages that didn't need it. Then today it struck me, this setup means when a new user clicks an internal link, they won't be able to use their cached stylesheet and will have to download a new stylesheet for every page.
Obviously this isn't the way forward, does anybody know a better way of doing it? I've considered using session data, but I'd rather not because if anybody had cookies off it would break. I've also considered using $_SERVER['REQUEST_URI'] in the stylesheet but I'm worried about false positives.
Any ideas would be appreciated. Thanks!
I am pretty sure that caching is always better then serving up dynamic spreadsheets.
The bottleneck in pretty much every webapp is bandwith/latency. So not having to request a file is better then serving a lot of perhaps smaller files that may require a bit less processing power.