3

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 ?

Operter
  • 95
  • 7

1 Answers1

3

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.

No Name
  • 612
  • 6
  • 15
  • 1
    If anyone can provide more details I will add them to my answer. I'm not super familiar with encoding problems. – No Name Aug 07 '18 at 20:18
  • Thank you so much. And it looks like it was getting inserted at the beginning of the because I was using user generated content inside the meta title and description tags, and this fixes that too :) – Operter Aug 07 '18 at 20:38