Does anybody know of an automated way of telling whether a PHP script is being called directly (as a HTML page), or as a JavaScript, or as a CSS Stylesheet?
Without GET variables, or setting a flag in the file ( that is what I am doing right now).
Just curious.
EDIT: Some background because it was asked for in answers: The reason why I want this is a framework that I use when serving HTML pages as well as when serving CSS files. This frameweork has a custom error handler. When I’m in JS “mode”, I would like to throw errors as a JS alert(). When I’m in CSS mode, maybe a red body background or something. I would like to avoid working with flags (?mode=css) or constant definitions for the sake of code cleanness, but several answerers have confirmed that there is no “magic” way of finding out what a resource is being used for.
If I understand you correctly, you have a page which calls itself, (like this):
In that case, no, there’s no way to tell – the browser sends a request saying
GET /page.php. No intent is mentioned – just “give me the page and the browser will decide what to do with it”. (yeah, yeah, there isAcceptand whatnot, haven’t seen a modern browser actually using this feature to say “give me this page as CSS”, most just sayAccept: */*)If you insist that all your output, be it JS, CSS, or HTML, should be generated with one file, I suggest an URL rewriter (assuming Apache HTTP server, this would be mod_rewrite; most platforms offer this functionality in some way or another). Example using mod_rewrite:
This way, request to
/css/style.csswill look likepage.php?type=css&file=style.csswhen your script is run, similarly for/js/foobar.js.(Technically, you’re still using GET variables to find out if the result is supposed to be HTML,JS,or CSS; but it’s not visible to the users, plus you get around some older browsers’ limitation “if query string, don’t cache or cache brokenly”)