Security Refactoring

Learn how to use the built-in HTML5 features to validate a form and how to use htmlspecialchars() to protect applications against an XSS attack.

Escape HTML with htmlspecialchars()

Before diving in, we have to remember the programming golden rule:

“Never trust user input.”

Let’s see why.

Imagine that a user types the following as their title project into our form: <script>alert('Hello world')</script>. What do you think will happen when the user submits this form? Let’s try it on the “add project” page to see for ourselves.

As we can see, if a malicious user succeeds in executing a script, not only they will annoy every user who arrives at the page in question, they could attempt to get those users’ cookies. To prevent this security risk from emerging in our application, we’ll use the PHP htmlspecialchars() function. This function will do the job of converting some characters like <, >, and & to their corresponding HTML entities. Let’s look at this function in action:

Get hands-on with 1200+ tech skills courses.