<\/script>')

How to encode url as javascript string in PHP generated HTML?

Given this PHP code:

<a onclick="javascript:window.location.href='<?php echo $url;?>'"

      

What if there is '

in $ url?

I tried to use json_encode($url)

but it can't handle it.

+2


source to share


1 answer


json_encode

will work. You just need to use it correctly:

<a onclick="javascript:window.location.href=<?php echo htmlspecialchars(json_encode($url)); ?>">

      



This will work as it json_encode

already returns a quoted JavaScript expression. And htmlspecialchars

it is necessary to avoid possible HTML metacharacters.

+3


source







All Articles