I am probably using it wrong, the problem is this:
I have php code that gets echoed to the page like so:
<?php echo "<h1>" . htmlspecialchars($array['text']) . "</h1>" ?>
That variable gets echoed from the databse in an html structure like this
echo "<h1> Hello </h1>"
This works fine, but as soon as I echo something like "> text here"
everything breaks. The text appears at the beginning of the body and I can actually inject JS into it and .. it works.
I have no idea what I'm doing wrong, am I using htmlspecialchars
wrong or is the problem from somewhere else ?
Use the following:
htmlspecialchars($string, ENT_COMPAT,'ISO-8859-1');
This makes htmlspecialchars
use ISO-8859-1
encoding, which I assume is what you're using.
Regarding the third argument, called encoding
, according to the htmlspecialchars docs:
If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.