0

How does using htmlspecialchars() stop XSS attacks?

Based on everything I researched, using this function allows you to render user input. According to my understanding, this means that if a user entered some html code into a form (or other input source), then you'll actually execute that code instead of simply displaying it. Again, how does this stop an attack?

If you look at the difference between using the function and not using it, clicking View Source gives you the following (on a call to `exec("dir") on a windows machine): Using htmlspecialchars() Not using it

As you can see, the difference is that <DIR> turned into &lt;DIR&gt; after using the function. So all it's doing is escaping all HTML characters? So it doesn't actually render anything? Would love a comprehensive answer to this.

nba
  • 3
  • 3
  • 1
    Where did you get that? **PHP doesn't execute HTML.** Neither htmlspecialchars "renders" anything. – Your Common Sense Mar 15 '23 at 09:11
  • While most answers in the linked dupe only say that you should escape input, not many explain why. [Matt E's answer](https://stackoverflow.com/a/45512141/240443) does a pretty good job, though: by escaping HTML characters, it prevents rendering ` – Amadan Mar 15 '23 at 09:15
  • 1
    Also, only very unsuspecting users escape "input" or, worse yet, "user input". To protect from XSS you must escape ANY data going to be used in HTML context. So it's a very specific **output**, not input and **any data**, not only the "user supplied" one. – Your Common Sense Mar 15 '23 at 09:17
  • 1
    Yes, "all it's doing is escaping all HTML characters", so they don't interpreted as commands by the browser. That's all. HTML is interpreted (or rendered) by the browser, not PHP. – Your Common Sense Mar 15 '23 at 09:23
  • 1
    [The Great Escapism (Or: What You Need To Know To Work With Text Within Text)](http://kunststube.net/escapism/) – deceze Mar 15 '23 at 09:24
  • `how does this stop an attack`....by neutralising the content, so it no longer contains anything a browser could execute, if/when that content comes to be sent to a browser. – ADyson Mar 15 '23 at 09:26

0 Answers0