View Full Version : Can php be used inside javascrpt?

10-09-2013, 06:04 PM
Is it possible to insert a bit of php inside a javascript? For example:

<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push(['_setAccount', '<?php echo $ga;?>']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);



10-09-2013, 06:10 PM
Yes, if the JavaScript is in your web page :)

10-09-2013, 06:26 PM
Thanks. So my example would work as written?

10-09-2013, 06:29 PM
To expand on what Beverley said, yes, as long as it's within a page that is processed by PHP. An external .js file usually isn't, although (in some complex ways) it is possible to circumvent that, either by a server setting or by using a .php file as an external Javascript file (with the right headers).

Usually I just put it in the head section of my page, even if everything else is external-- it's usually just a variable or two that I am pre-setting, so that's fine.

On the other hand, the order of operations is crucial!

PHP executes on the server, then everything (after the PHP is done) is sent as plain HTML (+JS/CSS) to the user. Only after that does any CSS or Javascript execute.

Therefore, there are two scenarios:

1. You want to have dynamic Javascript, either by having some value retrieved by PHP and inserted into the Javascript or by modifying the Javascript itself (eg, "do I want this script or this one?"). All of that is fine, as long as you do this before any of the Javascript is processed. Once the page loads, it will be static, no longer referring to PHP any more, but just to whatever the [original] output of the PHP was, when it was originally processed.
You can write Javascript (or part of Javascript) with PHP just like you write HTML with PHP. Same with CSS.

2. You need to use Javascript to run PHP code in real time. Perhaps you want Javascript to check right now, what time is it on the server?. This must run with Javascript, while the page is already loaded. Technically, this is impossible. You cannot run PHP, a serverside language, with Javascript, after the page has been processed. The only possibility is reloading the page and getting a new value from PHP and going from there.
However, there is a workaround: Ajax. Ajax allows you to use Javascript to send a new request to the server, but instead of loading a whole new page, you just get some data back (probably as a short string of text, perhaps some HTML elements) and then can manipulate that using Javascript. This requires creating a new, secondary PHP script that does only that section (rather than generating the whole page!). [NB: you can create this then use an include() to include that into the original full PHP, rather than having two unrelated independent copies of the same procedure.]
Ajax is somewhat complicated to use, varies by browser (at least the older ones), and is subject to security restrictions (primarily the 'only from the same server/domain' requirement).

So, in short, yes, you can. But the details matter.

The code you posted above will do exactly this:
1. PHP will retrieve whatever $ga is.
2. PHP will output that into the Javascript.
3. PHP will then serve the entire page to the browser.
4. The Javascript will operate as if that were a static value [except that it would possibly change every time you reload the page].

What you did there will not work at all for the purpose of "Javascript asking PHP for a value". Rather, it only works for "PHP [originally] telling Javascript something."

10-09-2013, 07:29 PM
Your example will work as long as $ga is set to something that makes sense to the script. I think that's the only PHP variable you have there. If I missed another one in the javascript code, it must also resolve to something that makes sense to the script. And of course this must be on a page that's processed by the server as PHP, like index.php, contact.php, or about.php, etc., any page with the .php extension.

Not directly related to your question (I mention this mostly because Daniel brought it up):

Your javascript is an on page script. So you do not have to worry about an external javascript using PHP. But it's not all that hard to have an external javascript that's also processed as PHP. Simply give it a .php extension and a javascript header*, and it will be. Then you just have to make sure that whatever PHP that it has in there that becomes javascript when interpreted by the server, actually makes sense as javascript.

header("content-type: application/x-javascript");



for an admittedly complex example of an external javascript that also uses PHP. But the concept of making it use both is simple.

10-10-2013, 01:07 AM
John, you're right that it's not that complicated. It's just usually not worth it (when you can easily put it in your page). Additionally, there's a reason to avoid that: you don't want to be dynamically generating your Javascript every time (especially if it's very long). Instead, just getting one value within the main page, and then using an external .JS file for everything else makes sense. But technically, it's possible, and not too hard. You also must, of course, then use a .php Javascript HREF in your HTML reference to it. The only issue might be (third-party) scripts (already) expecting a .js file.

The other method, of asking your server to treat .js as .php is more complicated and not possible on many shared hosting accounts. It also obviously wastes resources for processing every .js file (most with no effect except increased processing) as PHP. Of course you can specify certain limits (like only in a certain folder, even just a certain file) but that's complicated. You can do this, by the way, using .htaccess (among other methods). It's the same way that you would get a .html page to be processed as PHP, and there's more info/tutorials out there about that.

On the other hand, regarding formatting, there actually is a more important point (thanks John for mentioning that because I overlooked it earlier):

Kuau, you already have single quotes around the PHP for where it is to appear. This is important (crucial even). So that's part of it. But the other part is escaping the PHP value for use in Javascript. It may be a non-issue if you know for certain you will only ever have, for example, numerical values. But if you ever have strings, especially user-generated input, you must be careful about two things:
1) Integrity of the script (if there's an ' in there, it might stop the script from working, at the very least).
2) XSS attacks-- if a clever user notices this, and can save content directly into where that JS appears, they can design it so that it will do other things with the Javascript code, such as trying to steal personal information, displaying an ad, and so forth.

The tricky part is that you must escape this with regards to the location in the Javascript, regardless of what the PHP is doing. Here you'd at least escape ' with \', but possibly more. And if the string already contains \', then it would end up with \\', thereby circumventing the escaping. Depending on how it will eventually be displayed (in the HTML?, adding even more complexity/layers to this) a good option is to use HTML entities to store any potentially problematic characters, so you have &quot; for quotes, etc.