Escaping JavaScript for PHP
Inline JavaScript can be hard to code around with PHP. There's a lot going on in an onClick handler, and quoting can be a huge problem. Lots of time you have a snippet like this:
<a href="#" onClick="doFunction('<?php echo $myVar; ?>')">
Imagine all the possibilities: what if $myVar
contains a single quote
character? A double quote? A double quote, followed by some HTML tags?
There are workarounds for escaping JavaScript using PHP, but mostly
inside <script>
tags.
Well, here's a sure-fire PHP function to encode any ASCII string:
function javascript_escape($str) {
$new_str = '';
$str_len = strlen($str);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . dechex(ord(substr($str, $i, 1)));
}
return $new_str;
}
So, let's use this function in our link:
<a href="#" onClick="doFunction('<?php echo javascript_escape($myVar); ?>')">
Let's say we have the assignment $myVar = "&?1xc'\""
. The user-agent
ends up with this link:
<a href="#" onClick="doFunction('\x26\x3f\x31\x78\x63\x27\x22')">
The string is ultra-sanitized, and your function gets the string you intended. You may wish to write another function that only escapes target characters, possibly single quote, double quote, and ampersand. I'll go with overkill for now.