Given this PHP code:
<a onclick="javascript:window.location.href='<?php echo $url;?>'"
What if there is a ' in $url?
I tried using json_encode($url) but it won't be able to handle this.
json_encode will work. You just have to use it the right way:
<a onclick="javascript:window.location.href=<?php echo htmlspecialchars(json_encode($url)); ?>">
This will work since json_encode already returns an JavaScript expression with quotes. And htmlspecialchars is needed to escape possible HTML meta characters.
htmlspecialchars will encode the inner double-quotes to ", so it'll be fine. Also, can we lose the pointless ‘javascript:’ label?htmlspecialchars function will encode double quotes with ". And " inside a attribute value is legal and will be interpreted as a double quote character. So title=""foo"" will be evaluated to the attribute value "foo" (with double quotes).json_encode('abc') returns "abc" (including the quote characters). htmlspecialchars then encodes that as "abc", but the problem is that he doesn't want the quotes there in the first place." inside the attribute declaration is interpreted as ". Just like any other character reference is interpreted as the character it represents. “Some authors use the character entity reference """ to encode instances of the double quote mark (") since that character may be used to delimit attribute values.” (See w3.org/TR/html4/charset.html#h-5.3) And the attribute declaration "location.href="…"" is interpreted as location.href="…".
<a onclick="javascript:window.location.href=…"anyways? Why not simply<a href="…"?