Is it a bad idea to use php in css documents? - php

I have created css page called style.php and included this the top:
<?php header("Content-type: text/css"); ?>
Does this make you cringe. Is it a terrible idea? I am doing this because I have created a CMS that allows the admin to control colors on pages (so the style.php script queries the database and grabs the hex values).
Any thoughts?

It's not a bad idea (subject to the notes about caching + content-type), but think about the cost of firing up a PHP instance (mod_php) or passing the script to an already running php (fastcgi style). Do you really want that overhead?
You might be better off writing a "cached" version of your CSS page to a static file, and serving that (or if you need per-page flexibility, selecting which style sheet to include; I assume your main page is PHP already)

This is a fine solution, just make sure that you are serving up the appropriate headers. See my blogpost about a related topic (search for "The important headers are" to get to the right section).
One more thing:
With the caching you might get into the situation where the user changes the color she wants to see, but (because it is cached at the client), the page doesn't update. To invalidate the cache, append a ?=id at the end of the URL, where ID is a number that is stored for the user (for example in the session) and is incremented every time she changes the color scheme.
Example:
At first the user has a stylesheet of http://example.com/style.php?id=0
When she changes the colors, she will get the url of http://example.com/style.php?id=1 and so on.

Assuming you use appropriate caching, as I imagine the CMS-driven values will probably not change very often, there's no specific reason to avoid creating a CSS include on the fly.

This is not a bad idea. This is a creative idea with numerous benefits:
your users can define values w/o you needing to worry about security (parsing css is hard)
you can enforce a more visually consistent set of skins (some flexibility is better than total flexibility)
simple to code

Related

Why do some websites have link files like "afs342sf.css" instead of "main.css"?

I have partial understanding of why a developer will have a filename like afs342sf.css opposed to something more readable like main.css - I do not believe that the developer named the file manually; I'm sure it was done programmatically upon insert into whatever database. I'm a bit baffled on why this would be needed, and how it will be called.
If a database has a table with, and excluding others for simplicity:
file_id, file_name, file_display_name, file_size.......... etc.
When called for data it's using file_display_name (afs342sf.css or simply afs342sf) as a reference - href="/yourhost/www/afs342sf.css" - what on earth is the difference when someone can easily use the same GET request info, or have I got this theory all wrong? - I'm a paranoid one typically (apparently good for security) and have confused myself because it could also be the id for it, but isn't that giving away too much? Then there's the thought of what if the program changes the filename upon every request; could it get lost when other requests are incoming, and it doesn't have a fixed address name?
Last but not least, I would much appreciate it if anyone could post any links to pages that could help with stealthy, or concealed file retrieval methods. For the record I do not hide the .php extension - being self taught and learning from a trusted community is overwhelming for knowledge.
You're right, it's not named manually. Arbitrary filenames like that usually mean they are generated with a tool like Assetic. This is primarily used for files that have to be converted before being put on the web (SASS to CSS; Coffeescript to Javascript).
Assetic also has a cache-busting plug-in that generates filenames based on the hash so when the contents change, browsers will be forced to fetch the new file (this is a standard cache-busting technique). This is useful because static files usually have long expiry dates, and there's no other way to alert the browser that the file has changed.

Would A "style.php" Be Valid?

I had a thought...
Dunno if it's a good one or a bad one.
I am working on an image-less/responsive theme, for a SMF Fork. I was thinking since it's written in PHP, would it be valid to add php include a "style.php" in the header, containing the all the styles for the pages.
I was thinking this would give me two major benefits. One, would be that I could add variables start to the css file. Two, it would be one less HTTP request. I know that pagespeed and yslow would bitch about the css being included inside the page in between tags, but it is none the wiser, correct?
As far as I can tell, I see alot of benefits in doing it this way regardless of what pagespeed/yslow thinks. I could even do this with javascript, maybe...
I wonder if the IE maximum 4096 CSS rules would still apply?
I am a PHP Ultra Noob, but have a good amount of experience in web design. I can't seem to fine a reason "not" to do it. Any experts willing to share their thought on this idea?
I don't think it's a good idea. If you want to use variables in your CSS, look at SASS or LESS. Regarding the additional request, CSS is static, so if you do your job on the server side, the browser will retrieve the CSS only once, and subsequent requests will use the cached copy.
I don't think this can be harmful, however that's quite a diverge from standard development, so it's not a good idea just for this. Also, since nobody does it, is must not be such a smart invention.
A css file is generally more valid for better speed, because it is requested but once, and then cached for a long time. It is 1 extra request for the whole browsing session if they haven't got in in their cache already compared to the same css over and over and over again in the head tags, making your actual pages load slower. All in all, after a few requests a separate (cachable) file usually already wins out, provided you set it to be cachable for a long time (don't worry about people not seeing css changes, if you change your css, just add some query parameter like /styles.css?rev=1. You don't use that parameter, you just increase it whenever your css changes thus making the client request a fresh copy.
That doesn't mean you can't use PHP (or nodejs/less for that matter) to create or serve your CSS file, variables are indeed nice to have. If going the less route, DO convert it to css once on your own server instead of bothering clients with heavy javascript to convert it again and again.
You can actually include anything as a CSS file if it's valid CSS (and actually even if it's not, I suppose):
<link rel="stylesheet" type="text/css" href="/style.php">
//style.php
<?php header('Content-type: text/css');
$style = 'bold';
?>
strong {
font-weight: <?php echo $style ?>;
}

Why aren't PHP files used for (custom) CSS and JS?

Why don't people make .php files for their CSS and JavaScript files?
Adding <?php header("Content-type: text/javascript; charset: UTF-8"); ?> to the file makes it readable by browsers, and you can do the same thing to css files by setting the Content-type property to text/css.
It lets you use all the variables of PHP and methods into the other languages. Letting you, as an example, change the theme main colors depending on user preferences in css, or preloading data that your javascript can use on document load.
Are there bad sides of using this technique?
People do it more often than you think. You just don't get to see it, because usually this technique is used in combination with URL rewriting, which means the browser can't tell the difference between a statically-served .css file and a dynamic stylesheet generated by a PHP script.
However, there are a few strong reasons not to do it:
In a default configuration, Apache treats PHP script output as 'subject to change at any given time', and sets appropriate headers to prevent caching (otherwise, dynamic content wouldn't really work). This, however, means that the browser won't cache your CSS and javascript, which is bad - they'll be reloaded over the network for every single page load. If you have a few hundred page loads per second, this stuff absolutely matters, and even if you don't, the page's responsivity suffers considerably.
CSS and Javascript, once deployed, rarely changes, and reasons to make it dynamic are really rare.
Running a PHP script (even if it's just to start up the interpreter) is more expensive than just serving a static file, so you should avoid it unless absolutely necessary.
It's pretty damn hard to make sure the Javascript you output is correct and secure; escaping dynamic values for Javascript isn't as trivial as you'd think, and if those values are user-supplied, you are asking for trouble.
And there are a few alternatives that are easier to set up:
Write a few stylesheets and select the right one dynamically.
Make stylesheet rules based on class names, and set those dynamically in your HTML.
For javascript, define the dynamic parts inside the parent document before including the static script. The most typical scenario is setting a few global variables inside the document and referencing them in the static script.
Compile dynamic scripts into static files as part of the build / deployment process. This way, you get the comfort of PHP inside your CSS, but you still get to serve static files.
If you want to use PHP to generate CSS dynamically after all:
Override the caching headers to allow browsers and proxies to cache them. You can even set the cache expiration to 'never', and add a bogus query string parameter (e.g. <link rel="stylesheet" type="text/css" href="http://example.com/stylesheet.css?dummy=121748283923">) and change it whenever the script changes: browsers will interpret this as a different URL and skip the cached version.
Set up URL rewriting so that the script's URL has a .css extension: some browsers (IE) are notorious for getting the MIME type wrong under some circumstances when the extension doesn't match, despite correct Content-Type headers.
Some do, the better thing to do is generate your JS/CSS scripts in PHP and cache them to a file.
If you serve all of your CSS/JS files using PHP, then you have to invoke PHP more which incurs more overhead (cpu and memory) which is unnecessary when serving static files. Better to just let the web server (Apache/nginx/lighttpd/iis etc) do their job and serve those files for you without the need for PHP.
Running the PHP engine does not have a zero cost, in either time or CPU. And since CSS and JavaScript files usually rarely change, having them run through the engine to do absolutely nothing is pointless; better to let the browser cache them when appropriate instead.
Here’s one method I’ve used: The HTML page contains a reference to /path/12345.stylesheet.css. That file does not exist. So .htaccess routes the request to /path/index.php. That file (a) does a database request, (b) creates the CSS, (c) saves the file for next time, (d) serves the CSS to the browser. That means that the very next time there’s a request for /path/12345.stylesheet.css, there actually is a physical static file there to be served by Apache as normal.
Oh, and whenever the styles rules are edited (a) the static file is deleted, and (b) the reference ID is changed, so that the HTML page will in future contain a reference to /path/10995.stylesheet.css, or whatever. (Actually, I use a UNIX timestamp.)
I use a similar method to create image thumbnails: create the file on first request, and save a static file in the same place for future requests. I’ve never had occasion to do the same for javascript, but there’s no fundamental reason why not.
This also means that I don’t need to worry about caching headers in PHP: only the first invocation of each CSS file (or image thumbnail) goes through PHP, and if that is served with anti-caching headers, that’s no great problem.
Sometimes you might have to dynamically create javascript or styles.
the issue is webservers are optimized to serve static content. Dynamically generating content with php can be a huge perforamce hit because it needs to be generated on each request.
It's not a bad idea, or all that uncommon, but there are disadvantages. Caching is an important consideration - you need to let browsers cache when the content is the same, but refresh when it will vary (e.g. when someone else logs in). Any query string will immediately stop some browsers caching, so you'll need some rewrite rules as well as HTTP headers.
Any processing that takes noticeable time, or requires a lock on something (e.g. session_start) will hold up the browser while it waits for the asset.
Finally, and quite importantly, mixing languages can make editing code harder - syntax highlighting and structure browsers may not cope, and overlapping syntax can lead to ugly things like multiple backslash escapes.
In javascript, it can be useful to convert some PHP data into (JSON) variables, and then proceed with static JS code. There is also a performance benefit to concatening multiple JS files ago the browser downloads them all in one go.
For CSS, there are specific languages such as Less which are more suited to the purpose. Using LessPHP (http://leafo.net/lessphp/) you can easily initialize a Less template with variables and callbacks from your PHP script.
PHP is often used as a processor to generate dynamic content. It takes time to process a page and then send it. For the sake of efficiency (both for the server and time spent in programming) dynamic JS or CSS files are only created if there isn't a possible way for the static file to successfully accomplish its intended goal.
I recommend only doing this if absolutely you require the assistance of a dynamic, database driven processor.
The bad sides: plenty, but to name just a few:
It'll be dead slow: constructing custom stylesheets for each request puts a huge load on the server, not something you want.
Designers create CSS files, programmers shouldn't (in some cases shouldn't be allowed to). It's not their job/their speciality.
Mixing JS and PHP is, IMHO, one of the greatest mistakes on can make. With jQuery being a very popular lib, using the $ sign, it might be a huge source for bugs and syntax errors. Besides that: JS is a completely different language than virtually any other programming language. Very few people know how to get the most out of it, and letting PHP developers write vast JS scripts often ends in tears. JavaScript is a functional OO (prototypal) language. People who don't full understand these crucial differences write bad code as a result. I know, because I've written tons of terrible JS code.
Why would you want to do this, actually? PHP allows you to change all element's classes while generating the page, just make sure the classes have corresponding style rules in your css files and the colours will change as you want them, without having to send various files, messing with headers and all the headaches that comes with this practice
If you want more reasons why you shouldn't do this, I can think of at least another few dozens. That said: I can only think of 1 reason why you would think of doing this: it makes issues caused by client-side cached scripts less of an issue. Not that it should be an issue in the first place, but hey...

How can I add a flag to a URL?

I'm setting up a website where visitors will be greeted by a splash screen where they will choose a color scheme for the actual website; based on their selection, the actual website will load with a different stylesheet. I gather this can be done by concatenating a flag to the URL, then reading the flagged URL on the next page to determine the stylesheet to be loaded (for example, to load the dark theme, the url would become http://www.mywebsite.com/index-dark; clicking the light theme link would make the URL http://www.mywebsite.com/index-light. Problem is, I don't know how to add a flag to a URL, or how to read this flag on a different page. I've tried Googling the issue, but have found little practical information. How can this be done?
EDIT: I'd like to avoid using two separate pages, as I'll have multiple themes; that would mean copying basically every HTML page in my root multiple times, taking up space. I like the idea of a concealed $_GET variable, though.
Without more information, I can only give some general advice.
So I'm going to assume that you are building a page in PHP, so you could have two different urls and use mod_rewrite to convert /index-dark to /index?style=dark but that's crappy.
What you probably want is to use a cookie or a session. Basically you check a cookie, or session value, for the theme setting and then pick the appropriate CSS file when you generate the page.
This has several advantages:
Doesn't require using url rewriting, an error prone endeavour at the best of times
Allows for persistent setting (if you use a cookie) and doesn't involve complicated urls.
Allows for adding more themes without changing mountains of code, just add the setting to theme selector and the new CSS file.
GET variables are generally only useful for specific data sent with that request, a bit like POST variables are mostly for forms and submitted data. If you want persistent settings, then a session/cookie is the best option.
The "flags" you're mentioning are probably actually $_GET variables that have been disguised using mod_rewrite. What you can do is edit your .htaccess file to add in rewrite rules that change, say, www.mywebsite.com/index.php?style=index-dark to www.mywebsite.com/index-dark (unfortunately I don't have experience in how exactly to do this; I just know that it can be done) and have your PHP catch $_GET['style'].

How to store custom page headers

Another 'design' question.
(Technologies in use: PHP, MySQL)
I need to allow customers to customize the looks of their pages' headers. What is the best way to store such customized headers (say pieces of html closed in a div). Is storing them in database any good?
Or would it be better to store them in php files and include them to each page instead of default header?
Or perhaps allowing users to edit html is a very bad idea and I should use some other means for allowing them to customize their headers? (mostly they use it to put a logo + some additional information, sometimes animated gif with advert, sometimes just text... no rule).
Please advise.
Storing them on the local filesystem is the most performant and simpler one, so you may want to go with this one.
However this will not be as good once you have to scale on multiple servers. The better solution then is to use some kind of shared storage (the mysql database solution), and to eventually cache the templates somewhere.
Html in a database is bad practice it might brings encoding issues (not too hard to resolve but still, a pain in the a##).
what you should do is define the level of customization you want to achieve and create the php classes that will allow you to create such a customized header from your code.
You will then have to store in your DB the values needed to rebuild this header on the fly.

Categories