<?php
include 'components/server.php';
Is it possible to make it include server.php for desktops and server-mobile.php for mobile devices?
While technically possible, it's absolutely not the best way of doing things.
Why?
Because PHP runs on the server and only the output of that PHP execution is given to the browser. You would probably be wanting something using javascript which can load and then seamlessly react to the browser conditions, such as screen size and/or dimensions.
If you're trying to change which PHP script is running based on the browser criteria (as mentioned above) this sounds very much like your programming logistics are simply wrong.
If you somehow really do need to change PHP script execution based on end-client (browser) characteristics you could do this by calling a script based on javascript AJAX or using mechanisms mentioned in comments above, but as said, you're almost certainly "doing it wrong".
Alternative
It would be far better to load everything you need in PHP and then pass all of that content to the browser (as output; HTML, CSS, Javascript, etc.) for the Javascript in the browser to then decide which parts of the data it needs to use and ignoring the others.
Conceptually, this seems like it should be pretty simple, but I keep finding myself in a catch-22 whenever I try to implement it. (Also, for a variety of reasons, I'd really like to handle this without jQuery or AJAX, if possible.)
On the client side, onload triggers a video to play and a picture to appear. Then, each time the user presses the space bar, a different video plays, until a certain point at which the spacebar triggers the next page to load.
On the server side, PHP arrays control which videos and pictures will be displayed (both the order within a page, as well as which set of videos, out of a total of 70 sets).
Currently, all the client-side action is controlled by a set of JS functions that are included in my html header. All the PHP functions are listed toward the bottom of my main page script. The kicker, though, is that the JS functions necessarily contain some PHP references. For example:
document.getElementById("ImagePort").innerHTML="<img src=Pictures/<? echo $_SESSION['TrialArray'][4] . ">"; ?>";
The issue here isn't the syntax; it's the information flow sequence. The problem is that when these PHP calls are in the header, they appear before the browser makes it to the part where I call the PHP function that assigns values to them. PHP then throws error messages that muck up the JS parsing.
So then the intuitive solution is to either move these JS functions lower down (to a footer, perhaps) or else call the PHP functions before the header loads. However, moving them to the footer didn't solve the problem for me. I sortof thought it would... am I mistaken in that expectation, or have I perhaps made a simple mistake somewhere?
Moving the calls such that they precede the JS function definitions is equally problematic, since then the script doesn't know what the JS functions are called, either by PHP or in HTML.
PHP example: playVid(source) is a JS function, $Instructions is a PHP variable.
if ($_SESSION['Page'] == 0) {
echo "<script>playVid(" . "'" . $Instructions . "'" . ");</script>";
}
HTML example: both setFocus() and ShowFirstStimulus() are JS functions.
<body onload="setFocus(); ShowFirstStimulus()">
Both of these throw an "Uncaught Reference Error: [function] not defined. Again, I'm trying to figure out whether that's because I simply can't do it this way, or if I've just made a mistake in how I've set it up.
Assuming that there really is no way out of this Catch-22 (where PHP functions can't be called before JS functions, and JS functions can't be called before PHP functions), it seems that one remaining option is to simply write some dummy code in which I initialize some PHP variables to some value that's bogus but parse-able. This seems like terrible coding hygiene, but at this point I'm not seeing many other options. Any suggestions?
Please also let me know if I need to clarify anything. Thanks!
I know JavaScript or CSS for expample can be "compressed", "simplified" in order to be loaded faster. After simplifying they are difficult to be read by humans... and this is exactly what I need.
Is there anyway to make it automatically? Rename all variables to short random strings and make it all hypercompressed. I don't think it is a fool thing because I have seen this lot of times in javascript. The idea is to conserve the original source and upload the minified one.
There is no need for doing this. The Server reads the file, and the file never gets transferred to the user.
Therefore, compression is useless because there is no bandwidth saved.
CSS & JavaScript does however get transfered to the user, and therefore they can see it. A user can never see PHP unless you've done something wrong on your server. But then you need to worry about totally different things than compression.
If you want to compress it, this is basically useless, since you have it on the server and only the output gets transferred to the client.
If you want to make the code more difficult to read for other human beings, you're looking for something which is called an obfuscator.
There are a few php obfuscator engines out there, p.e.
http://www.codeeclipse.com/
http://www.truebug.com/
http://www.raizlabs.com/softwarephpobfuscator/
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...
I was wondering if I can use PHP and Javascript to get the screen resolution from my users. Altho this is a simple thing, I was wondering if I can execute the JavaScript within a PHP statement and not output the Javascript code to the browser as HTML
I thought maybe putting it in an EOF block, but that didn't work, the output was the actual script haha.
I want to be able to populate a $width and $height within my PHP script and create a variable to look something like
$resolution = 800x600
I know I can place the javascript in the HTML page and then have a PHP block capture the javascript output, but I am using the Smarty template engine and have disabled the use of PHP within the templates for security reasons.
Is there a way to accomplish this?
I don't want to use the resolution for any url manipulating but rather to store the information for my statistical reasons.
I don't think what you want is really possible. It has to be in the HTML output for the browser to execute it.
You can capture it in the page JavaScript and use an AJAX call to POST it back to the server... but at that point you may as well use Google Analytics, because I'm pretty sure that's essentially what they do (but their framework is supported by, well... Google). Using Google Analytics will also prove to be useful, since they capture a number of other statistics as well.