ipel ipel - 1 year ago 59
Javascript Question

php & javascript alert that contains a string with double quote

This is an example of string that should I output in a javascript alert();

string with "double quote" in it

Because this string can be edited via PHP by my users it's better to prevent XSS attacks. To do so in the HTML of my document I usually do:

<?php echo( htmlspecialchars( $MY_STRING, ENT_QUOTES, 'UTF-8' ) ); ?>

That works great.

But now I just noticed that if I output the same string in a javascript alert:

alert( "<?php echo( htmlspecialchars( $MY_STRING, ENT_QUOTES, 'UTF-8' ) ); ?>" );

The output of the alert in this case is:

string with &quot;double quote&quot; in it

What is the best way to output the double quotes in a alert, but also preventig XSS injection?

Answer Source

ENT_NOQUOTES flag ensures all quotes ' and " are not escaped and the addslashes escapes them for the js alert function.

$string = 'string<< with "double quote" in it';
echo htmlentities(addslashes($string), ENT_NOQUOTES);


string&lt;&lt; with \"double quote\" in it

Keeps your quotes and escapes malicious html tags