简体   繁体   中英

Escaping Javascript in PHP

I'm looking for the best way to escape some Javascript text in PHP, and json_encode is the wrong tool for the job.

The problem comes from this line:


echo " onclick=\"SwitchDiv('" . $option . "')\"";
If there's an apostrophe in $option , this is a juicy ball of client-side fail. But doing a straight json_encode (which works perfectly well in other contexts) doesn't help:
 echo " onclick=\\"SwitchDiv(" . json_encode($option) . ")\\""; 
That creates an output string of onclick="SwitchDiv("athlete's foot")" , resulting in premature termination of the onclick value. (Which also happens if I enclose the onclick value in single quotes.)

Is there an elegant way around this? Should I just funnel the json_encode output through a regex that will escape the single quotes?

json_encode is the right tool for the job. Your problem arises from the fact that you are also including that Javascript in an HTML attribute , thus it also needs to be htmlspecialchars -encoded.

echo " onclick=\"SwitchDiv(" . htmlspecialchars(json_encode($option)) . ")\"";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM