Is htmlspecialchars required if you are not outputting html?
Question by user1278496
I have a script that registers users based on their user input. This uses prepared statements plus whitelists to prevent sql injection. But I am struggling to understand the prevention of XSS.
From what I understand, you only need to prevent XSS if you are outputting HTML onto the page? What does this mean???
Im guessing that with this register page it doesn’t apply because I am not outputting HTML to the web page? Is that right?
If I was to prevent XSS, do I use htmlspecialchars?
Answer by JT Smith
Generally correct, if you are having any returned values show up on the page, or if you are inserting information into the database for later retrieval and display (like user profile information) you will want to use htmlspecialchars.
For me, when I do my user registration, if they fail to enter a correct value in an input field, I redisplay the page with the values they entered. In this case, I have it encoded with htmlspecialchars.
If at any point ever, you plan on redisplaying the information from the DB into a webpage (as mentioned with profiles and the like) you should use htmlspecialchars.
Better safe than sorry I always say – never trust user input
Answer by Starx
Basically, XSS happens when you are taking the user’s input un-sanitized and display in your webpage.
For example: A user inputs
<script>alert('hello you are hacked');</script>
In a text box, and you show this in your webpage after it is registered like
Hello, $username
This suddenly gets turned into
Hello, <script>alert('hello you are hacked');</script>
This is one of the form of XSS
One of a effiecient way to prevent XSS is like this
echo htmlspecialchars($varname, ENT_QUOTES, 'UTF-8');