Search⌘ K
AI Features

Security Refactoring

Discover how to refactor your PHP CRUD application to improve security by escaping user input with htmlspecialchars. Learn to prevent cross-site scripting attacks and duplicate database entries through validation and unique constraints. This lesson helps you apply secure coding practices within your PHP app to protect both users and data integrity.

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() ...