4

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:

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

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?

ipel
  • 1,326
  • 1
  • 18
  • 43

3 Answers3

3

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);

Output:

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

Keeps your quotes and escapes malicious html tags

Roy
  • 3,027
  • 4
  • 29
  • 43
0
alert( "<?php echo( addslashes( $MY_STRING ) ); ?>" );

Use addslashes() rahter than htmlspecialchars() or combine both. Hope it helps.

addslashes() http://php.net/manual/en/function.addslashes.php

Eisa Adil
  • 1,743
  • 11
  • 16
0

Everything inside alert is treated like a string and won't be executed, so you won't get an XSS attack if you just make sure it's a singlestring by just escaping the "

For an alert you don't need to use htmlspecialchars, you can just do it like this:

<script>
    alert( "<?php echo addslashes($MY_STRING);  ?>" );
 </script>
Franklin Rivero
  • 581
  • 1
  • 3
  • 18