Given this PHP code:
鉴于此PHP代码:
<a onclick="javascript:window.location.href='<?php echo $url;?>'"
What if there is a '
in $url?
如果有$ in $ url怎么办?
I tried using json_encode($url)
but it won't be able to handle this.
我尝试使用json_encode($ url),但它无法处理这个问题。
1 个解决方案
#1
3
json_encode
will work. You just have to use it the right way:
json_encode会起作用。你只需要以正确的方式使用它:
<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.
这将起作用,因为json_encode已经返回带引号的JavaScript表达式。并且需要htmlspecialchars来转义可能的HTML元字符。
#1
3
json_encode
will work. You just have to use it the right way:
json_encode会起作用。你只需要以正确的方式使用它:
<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.
这将起作用,因为json_encode已经返回带引号的JavaScript表达式。并且需要htmlspecialchars来转义可能的HTML元字符。