Hiding JavaScript so that visitors can’t see it might not seem like a necessary precaution to take in most web programming situations. After all, a server-side language like PHP automatically prevents users from seeing your source code, and increasing functionality is quickly rendering the client-side advantages of JavaScript less significant by the day. However, there are many practical reasons to take the PHP-hidden-JavaScript approach, especially if you have long and complicated scripts that already exist and are in use, which would take a significant time commitment to revamp in PHP.
The key to this approach is to encapsulate your JavaScript in a separate PHP file, and to use a PHP session to restrict access to those scripts except when you want it to be explicitly permitted (i.e. when you want to run them from a specific page). To accomplish this, we first create a PHP session on the page from which we want to run the JavaScript.
< ?php
session_cache_limiter('none');
session_start();
if(!$_SESSION['allow_script'])
{
$_SESSION['allow_script'] = true;
}
?>
Placing this PHP at the top of your page opens a session and registers the variable ‘allow_script’ to that session, with a value of ‘true.’
The next step is to move whatever JavaScript you want to execute over to another file called ’script.php’ This file should contain your JavaScript wrapped in a PHP tag, along these lines:
< ?php
if(!$_GET['allow_script'])
{
session_start(); //restart the session from the previous page
}
if($_SESSION['allow_script']) //execute the javascript only if the variable is passed
{
header("Content-type: text/javascript");
?>
alert(”Hello World! JavaScript executed.”);
< ?php
}
?>
This portion of the PHP guarantees that the JavaScript generated by it does not appear to the end user, even if they navigate directly to script.php. The $_GET['allow_script'] check insures that the user is not trying to do an end-around by passing the allow_script variable with a value of ‘true’ directly to the script.php page, which would obviously allow them to view the JavaScript source.
Finally, you need to unregister the variable and close the session:
< ?php
$allow_script = false;
session_unregister('allow_script'); //delete the variable from the session
session_unset(); //make the session inactive
session_destroy(); //and toast it for IE
}
?>
NB: session_destroy() is not necessary for Firefox or Internet Explorer 6 or better, but leaving it out means that IE 5 users will be unable to reuse the script.php page without closing and re-opening the browser.
The end result of this simple process is a nicely hidden, encapsulated JavaScript that can be called with the simple line:
<script language="JavaScript" src="script.php">
Now your existing JavaScript (with all its client-side capability) can be easily referenced within your code, without leaving it vulnerable to the malicious efforts of prying eyes.