DEV Community

Cover image for Why you should always HTML encode your input
Tim
Tim

Posted on

Why you should always HTML encode your input

The website you just built might be a beautiful, well-coded masterpiece but the time it may take to break/crash is not very long without this piece of code.

You probably already heard of the topic: website security.
I will show you a simple trick that will work as a defense against hackers that try to break in or exploit your website using 'xss' (cross-site scripting).

Of course this is just a basic countermeasure and if you want to know more, google will guide you by typing in xss ;) . Also, this is my first post here so any advice or suggestions regarding my post are always welcome.

Now onto the more interesting stuff:

Let's say for example you have a section on your website where you ask for the user's input and show that exact input back to them (think of comments on a blog, etc). If we didn't sanitize the input given by the user, we would have a lot of problems.

What if the user were to type in "alert('oops')" for example?
Well, the comment that the website will show back will contain that very string which in fact will show nothing (an empty comment), what it will however do is give every user on the page a pop-up saying "oops".
Now, this is all very fun and not too serious yet, because the hacker could also start loading in malicious scripts and start modifying the page.

Now, take a look at this little test website:

This website will take whatever the user types into the input box and show it into a div below that box.

To sanitize that input in PHP is very simple, in fact we only need to use 1 function: htmlspecialchars();
Take a look at the following code snippet:

Now let's test it.

But what happened behind the scenes?

PHP changed '<' into '& lt;' and '>' into '& gt;'. Now HTML can properly show these characters without thinking it is an actual tag.

So there we go, we made our first step to a safer website!

Thank you for taking your time to read my post!

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.