BlairHippo
BlairHippo

Reputation: 9658

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?

Upvotes: 0

Views: 90

Answers (1)

lanzz
lanzz

Reputation: 43158

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)) . ")\"";

Upvotes: 3

Related Questions