views:

279

answers:

6

I have a php page, where at the bottom of the page I have some javascript code.

I use php inside the javascript code, like this:

alert ("<?php echo $variable; ?>");

If I put this in a separate file, this wont work for some reason. Is there anyway to make it work from a separate file without too much difficulty?

Or is there another way I don't know of yet to make javascript code invisible for the users? (for example so they cant see the code by viewing the source code)

Thanks

+8  A: 

Javascript is interpreted by the browser, so the browser needs to see the code. This means that it is also accessible by the user. You cannot hide JavaScript from the user. What you can do is obfuscate it, to make it difficult for the user to read the code.

Marius
+2  A: 

What did not work when you put that code in a separate file and what filetype did you use? If you used a PHP-file and included it, it should work, if you used a JS-file, it can't work, as JavaScript-files don't interpret PHP (which is server-side).

Apart from "obfuscating" JavaScript with a proper solution (there are some around, Google knows more :), I don't know of any way to "hide" the code as JavaScript is code that will be executed on the client side, so the client (browser) has the receive that code beforehand.

Select0r
it is a js file yes, but you mean I can just save it as a .php file which contains javascript, and then include it and it will work?
pesar
Yes, if you surround the above code with a JavaScript-<script>-tag. But still: the code won't be hidden from the user.
Select0r
A: 

Nowadays, with Firefox Firebug and Chrome (amongst others), you can see all the JS: no point in trying to "hide" it.

jldupont
A: 

You cannot make javascript invisible for the user, but you could use javascript encoder/packer to make your code very dificult to copy/understand by others.

Have a look at:

Example google script with shrinked variables and function names: http://www.google.com/ig/extern_js/f/CgJlbhICdXMrMO0BOAQsKzDyATgRLA/eklYcEESpHY.js

As you can see - it is very difficult to get what is it all about.. On the other hand - if someone really _really_ wanted, he could decipher it..

rochal
A: 

AFAIK if you want the browser to execute your javascript then the browser (and the users) must be able to read it.
However you may scramble the code with some tools like http://tero.co.uk/scripts/scrambler.php

Regards
Thomas

Thomas
A: 

Hey,

Not a PHP expert so sorry for my potential ignorange but the PHP code is server-side right? They would only see the client-side representation of that response. You cannot hide it from the user, and you cannot put PHP code in a JS file if that's what you meant by other file.

The only other option is to compress or use another tool to change the JS as mentioned previously.

HTH.

Brian