views:

195

answers:

1

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.

+3  A: 

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.

Gumbo
Er - what's the point of using location in the OP's context? Is this some sort of trick for storing the location in the browser's history when using ajax or some odd circumstance?
meder
@meder: Don’t ask me, ask the OP.
Gumbo
No,it'll generate something like onclick="javascript:window.location.href="blablabla..""
Misier
Say,quote inside quote.
Misier
`htmlspecialchars` will encode the inner double-quotes to `"`, so it'll be fine. Also, can we lose the pointless ‘javascript:’ label?
bobince
Do you think href=" is meaningful?
Misier
Can someone down vote this answer for me?
Misier
As bobince already said, the `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).
Gumbo
@Gumbo,but location.href=" is not legal at all!
Misier
@Gumbo: no, the problem is that `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.
Kip
@Misier: The `"` 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 http://www.w3.org/TR/html4/charset.html#h-5.3) And the attribute declaration `"location.href="…""` is interpreted as `location.href="…"`.
Gumbo
@Misier: So I am right after all?
Gumbo
@Gumbo aha, i was overthinking the problem
Kip
This is perfect answer. I'd like to see more people doing htmlspecialchars() on all values pushed to html and doing htmlspecialchars(json_encode()) on values pushed to javascript.
Kamil Szot
No,it's not,when it's faced with multibyte characters!http://stackoverflow.com/questions/1531881/how-to-make-jsconencode-work-with-multibyte-characters
Misier
@Misier: Only the event attributes beginning with `on…` are treated as JavaScript and will accept JSON data. But the `title` attribute value is not treated as JavaScript. So using `json_encode` is not right.
Gumbo