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

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...

Related

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 ?>;
}

Performance vs modularity: Integrate JS into PHP or separate custom.js

I am new to Javascript and development in general and have an absolute beginner's question: I would like to know more about the advantages and disadvantages of the following two constellations, especially regarding execution speed and server load/requests.
Put all custom JS code inside PHP code and call it from there
Put all custom JS code inside a custom.js and just call the JS functions in PHP
On the one hand I prefer to keep all my JS code separated to have things tidy and clean but on the other hand I imagine that it takes longer to load the page due to an additional server request. Will there be a noticeable speed difference when I put all code in a custom JS file? Are there any specific scenarios where it's recommend to put the JS inside the PHP or keep it separated?
Thanks
Http requests run in parallel, so loading a js file may not be noticeable at all, assuming you have to wait for images and other assets to load as well. The benefits outweigh the potential drawback.
As an added bonus, js files are normally cached, while html is reloaded each time a page is requested.
NOTE: If you have a significant number of scripts, you will have problems with load speed since browsers have limits of how many requests can be made in parallel. In this case you should be looking into minifying and combining them. Try code.google.com/p/minify for automatic minification using php.
Last: Having js code in php is terrible for maintainability.
JS in separate file - additional request. But I would not say that is a problem because it will be cached by browser. If you have a lot of js files - collect them into a single file to avoid multiple requests (there are special tools to compile separate JS files into one file and minimize its size).
Placing it into PHP code is just terrible. It should be in separate file.
On the one hand I prefer to keep all my JS code separated to have things tidy and clean but on the other hand I imagine that it takes longer to parse the whole code.
Why? JS is executed on client side. Not on server side. PHP will not parse JS files. At the same time - if you will put a JS code in PHP file - PHP will need to echo it to browser and that is additional work for PHP engine. Plus, in PHP code it will be sent to browser any time when PHP is executed.
Always err on the side of clean readable code, lest you fall into the premature optimization trap.
You can always refactor underperforming code to make it faster, it's much harder to move from low-level optimizations to a more abstract design, than the other way around (abstract to low-level)

where to include script files

i have divided various components of the page in different php file. In the navigation php file i have the objects i want to use in the javascript.
where should i put the javascript <script ...> so that it loads fine? right now i am putting it in a completely seperate file header.php? but i dont think the javascript is picking objects from nav.php
i hope i am making sense ;)
The standard suggestion is that you should put all of your SCRIPT links prior to your closing BODY tag at the bottom of your document. This streamlines network connections:
http://developer.yahoo.com/performance/rules.html
It doesn't matter where in the PHP rendering process you put it, it only matters that when the output HTML and javascript are combined, the HTML elements exist before you try to access them in javascript.
It's for this reason that most javascript toolkits have a function for executing javascript once the page elements are loaded, such as jquery's document.ready function.
Generally the advice is to put the <script> at the bottom of your HTML page.
http://developer.yahoo.com/performance/rules.html
My understanding is that the best speed comes from putting the script at the end of the page?
http://developer.yahoo.com/performance/rules.html
Put Scripts at the Bottom
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.
Noet that the performance benefit you gain from repositioning the tags (or using more esoteric methods for avoiding blocking) is very small compared to the benefit of getting them cached correctly at the browser.
C.

Are there any disadvantages of using PHP compared to html?

I have a few pages out (not too many though) and I was just thinking that I might want to change all of the pages to php instead of html. I am planning on using php in the future, I am just not quite ready yet to make it my full-time language. I know anythign you can do with html pages, you can do with php pages, but I just wanted to know, is there any reasons to stay with html compared to switching to PHP before my site gets too big and I wind up having to change 100 pages, and renaming hundreds of links?
The only reason I can think of is a small hit in performance.
Most web servers like Apache, LightTPD are configured to serve .html files as static files while .php files will have to first go through the PHP engine to be interpreted and only then delivered to the client.
Your pages will still be HTML. PHP allows websites to be generated dynamically, that is, you can display a username for users. However, what is sent to the browser is still HTML.
I recommend that you start switching to PHP because even if you choose not to use PHP, your pages will still work and render fine. However, if you stick with .html and then decide to switch to PHP, then you'll have to convert every single link. So convert now, and save time.
One thing I should note: It is possible, but usually not done, to have .html pages render as PHP by modifying server settings. However, in most cases, the .php is used, as most servers are already configured to run .php though the PHP engine. But in case anyone with a large site has this question, this is an option.
You pretty much answered your own question. If you ever reach the stage where you want to add dynamic content to an HTML document, you're going to need to change the file extension, or alter the webserver configuration to have PHP process .html files.
Generally, you will want every page to contain, if not dynamic content, then at least consistent content. Things like headers and footers, that require a massive amount of copy-pasting in straight HTML or a single include() in php. PHP allows for much cleaner organization and much less repetition, even if you're not after dynamic content for your pages.
The extension doesn't really matter. the PHP marker won't have any real effect until you begin embedding the tags into the files to engage the script processor.
Although it's true that you can do anything with PHP that you can do with HTML, the contrary is not true. With PHP you can do things that are not possible with HTML. Specifically, you can create dynamic pages with PHP, that is, pages whose contents are not fixed once you've written them.
If your pages are static, then you should continue to use HTML, if you need dynamic content, then you must use PHP (or another template/programming language).
why stay with just html when u can have both? u can have static html pages for static content and php pages for dynamic content. You can manage not just links but almost everything with php. I am creating a site with just 30 pages and I can say, while I do have both php and html, some things get out of hand (links, templates, data, etc). Imagine having 70 more...
Well, there aren't that many disadvantages maybe except for the fact that you might end up with this sort of code

Best Practice: Legitimate Cross-Site Scripting

While cross-site scripting is generally regarded as negative, I've run into several situations where it's necessary.
I was recently working within the confines of a very limiting content management system. I needed to include database code within the page, but the hosting server didn't have anything usable available. I set up a couple bare-bones scripts on my own server, originally thinking that I could use AJAX to import the contents of my scripts directly into the template of the CMS (thus retaining dynamic images, menu items, CSS, etc.). I was wrong.
Due to the limitations of XMLHttpRequest objects, it's not possible to grab content from a different domain. So I thought iFrame - even though I'm not a fan of frames, I thought that I could create a frame that matched the width and height of the content so that it would appear native. Again, I was blocked by cross-site scripting "protections." While I could indeed load a remote file into the iFrame, I couldn't execute JavaScript to modify its size on either the host page or inside the loaded page.
In this particular scenario, I wasn't able to point a subdomain to my server. I also couldn't create a script on the CMS server that could proxy content from my server, so my last thought was to use a remote JavaScript.
A remote JavaScript works. It breaks when the user has JavaScript disabled, which is a downside; but it works. The "problem" I was having with using a remote JavaScript was that I had to use the JS function document.write() to output any content. Any output that isn't JS causes script errors. In addition to using document.write() for every line, you also have to ensure that the content is escaped - or else you end up with more script errors.
My solution was as follows:
My script received a GET parameter ("page") and then looked for the file ({$page}.php), and read the contents into a variable. However, I had to use awkward buffering techniques in order to actually execute the included scripts (for things like database interaction) then strip the final content of all line break characters (\n) followed by escaping all required characters. The end result is that my original script (which outputs JavaScript) accesses seemingly "standard" scripts on my server and converts their standard output to JavaScript for displaying within the CMS template.
While this solution works, it seems like there may be a better way to accomplish the same thing. What is the best way to make cross-site scripting work specifically for the purpose of including content from a completely different domain?
You've got three choices:
Create a server side proxy script.
Create a remote script to read in remote dynamic HTML. Use a library like jQuery to make this easier. You can use the load function to inject HTML where needed. EDIT What I originally meant for example # 2 was utilizing JSONP, which requires the server side script to recognize the "callback=?" param.
Use a client side Flash proxy and setup a crossdomain.xml file on your server's web root.
Personally, I would call to that other domain on the server and get and parse the data there for use in your page. That way you avoid any problems and you get the power of a server-side language/platform for getting and parsing the data.
Not sure if that would work for your specific scenario...hard to know even with your verbose description...
You could try easyXDM, by including very little code, you can pass data or method calls between documents of different domains.
I've come across that YDN server side proxy script before. It says it's built to work with Yahoo's Search APIs.
Will it work with any domain, if you simply trim the Yahoo API code out? Or do you need to replace it with the domain you want it to work with?
iframe remote content can be accessed by local javascript.
The remote server just have to set the document.domain of the page.
Eg:
Site A contain an iframe with src='Site B/home.php'
home.php looks like this :
[php stuff]...[/php]
[script type='text/javascript']document.domain='Site A'[/script]

Categories