Passing PHP Variables to External JavaScript Files
Wednesday, October 14th, 2009Over the years, web development has morphed from static web pages that included content and style in one file, to large complex web applications that pull information from databases while adjoining multitudes of PHP, JavaScript, and CSS files. A developer’s Rubik’s cube is getting all of these different platforms that make up a modern day web page (MySQL, PHP, JavaScript and the DOM) to all talk to each other seamlessly, while keeping security in mind.
Typically, when a developer needs their JavaScript to access a variable contained within PHP, it requires an AJAX call to the PHP script which would return the variable(s) in JSON format. This method can sometimes be undesirable as it posses security vulnerabilities. Also, if the AJAX call is made on the page load, it’s just one more HTTP request slowing down the load speed of your site. There’s also the method of placing needed variables in a hidden input and then retrieving them from the DOM with JavaScript, but with the advent of Firebug, no hidden input is safe from malicious users these days. So how can we tackle these issues while still seamlessly integrating PHP and JavaScript? Easy. Have PHP parse your JavaScript files.
Create a .htaccess file in your JavaScript directory and add this line:
-
AddHandler application/x-httpd-php js
This tells the PHP parser to read files that have a ‘js’ file extension. Now you can simply set and unset $_SESSION variables to pass values to the JavaScript. For example:
PassPHPVarToJS.php
-
<?php
-
$myVariableThatJavaScriptNeeds = 42;
-
$_SESSION['myJavaScriptVar'] = $myVariableThatJavaScriptNeeds;
-
?>
-
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
-
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
-
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
-
<head>
-
<meta http-equiv=”Content-Type” content=”text/html;charset=utf-8″ />
-
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
-
<script type=”text/javascript” src=”js/index.js”></script>
-
<title>PHP to JavaScript variable passing</title>
-
</head>
-
<body>
-
Test
-
</body>
-
</html>
/js/PassPHPVarToJS.js
-
<?php
-
// Start PHP session
-
?>
-
$(document).ready(function(){
-
// Echo the session variable
-
var varFromPHP = <?php echo $_SESSION[‘myJavaScriptVar’]; ?>;
-
// Test
-
alert(‘This value is from PHP: ’ + varFromPHP);
-
<?php
-
// Unset the session variable
-
?>
-
});
This will securely alert the PHP variable to the user while avoiding using an additional HTTP request.
But what about passing arrays and objects? Not a problem. Example:
PassPHPObjectToJS.php
-
<?php
-
’someValue’ => “Bears”,
-
’someOtherValue’ => “Beets”,
-
‘someNestedArrayValue’ => “Battlestar Galactica”
-
})
-
});
-
$_SESSION['myJavaScriptVar'] = $ myObjectThatJavaScriptNeeds;
-
?>
-
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
-
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
-
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
-
<head>
-
<meta http-equiv=”Content-Type” content=”text/html;charset=utf-8″ />
-
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
-
<script type=”text/javascript” src=”js/index.js”></script>
-
<title>PHP to JavaScript variable passing</title>
-
</head>
-
<body>
-
Test
-
</body>
-
</html>
/js/PassPHPObjectToJS.js
-
<?php
-
// Start PHP session
-
?>
-
$(document).ready(function(){
-
// Echo the session variable
-
// Test
-
alert(‘This value is from PHP: ’ + objectFromPHP.someNestedArray. someNestedArrayValue);
-
<?php
-
// Unset the session variable
-
?>
-
});
PHP 5.2 and higher have built in JSON functions, so you can easily convert PHP variables to JSON. If you’re running on a lower version of PHP there are solutions out there that you can include in your page to achieve the same output.
That’s it! Your site just instantly became more secure while promoting low coupling and high cohesion. Now some might point out that this slows down your execution time due to the fact that PHP is now parsing extra files it normally wouldn’t parse, but I would argue that the extra parsing time is negligible, and that its quicker than making an unsafe and unnecessary AJAX call.



