Hide your JavaScript with PHP sessions
March 17, 2006 Web Programming No Comments
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
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
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
