2

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.

5
  • 5
    Why do you use this <a onclick="javascript:window.location.href=…" anyways? Why not simply <a href="…"? Commented Oct 6, 2009 at 17:25
  • If the user doesn't have JS enabled and you don't set an href, it won't go anywhere FYI. Commented Oct 6, 2009 at 17:30
  • 3
    Because this is a contrived example.I am using it on div actually. Commented Oct 6, 2009 at 17:32
  • @Misier: have you tried the solution I posted? Commented Oct 6, 2009 at 19:17
  • It looks like hardcode,is there a more elegant way to do it? Commented Oct 6, 2009 at 19:20

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

13 Comments

@meder: Don’t ask me, ask the OP.
htmlspecialchars will encode the inner double-quotes to &quot;, so it'll be fine. Also, can we lose the pointless ‘javascript:’ label?
As bobince already said, the htmlspecialchars function will encode double quotes with &quot;. And &quot; inside a attribute value is legal and will be interpreted as a double quote character. So title="&quot;foo&quot;" will be evaluated to the attribute value "foo" (with double quotes).
@Gumbo: no, the problem is that json_encode('abc') returns "abc" (including the quote characters). htmlspecialchars then encodes that as &quot;abc&quot;, but the problem is that he doesn't want the quotes there in the first place.
@Misier: The &quot; 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 "&quot;" 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=&quot;…&quot;" is interpreted as location.href="…".
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.