Here’s how to prevent XSS attacks by escaping output in PHP:
Here’s the code I used in the video:
What Is XSS?
XSS stands for cross-site scripting and it refers to a type of attack where a hacker injects malicious client-side code into the output of your page.
Applications that don’t escape their output are vulnerable to this type of attack.
XSS Example
A simple example is a blog comment. If not properly escaped, an attacker could enter (for example) JavaScript code into the blog comment.
That code would be stored in the database, output to the page when loaded, and because it’s not escaped… render and run.
Thus, the attacker would have the full range of JavaScript capabilities to attack you and your site visitors.
How to Prevent XSS Attacks
As illustrated in the video above, you prevent XSS attacks by escaping your output using htmlspecialchars() or htmlentities().
Both PHP functions convert problematic characters into HTML entities causing the injected code to be output harmlessly and not rendered.
htmlentities vs htmlspecialchars
Both will prevent XSS attacks. The difference is in the characters each encodes. htmlentities will encode ANY character that has an HTML entity equivalent.
htmlspecialchars ONLY encodes a small set of the most problematic characters.
It’s generally recommended to use htmlspecialchars because htmlentities can cause display problems with your text depending on what characters are being output.
Think of htmlspecialchars as a scalpel and htmlentities as a hammer. Both can solve the problem… one is just a little more precise.
If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.
This Post Has One Comment
Hey John, what’s up? That’s awesome…I was just casually googling whether to use htmlspecialchars() or htmlentities(), and your post appeared right at #1 above Stack Overflow and the “People also ask…” box! Congrats! Your SEO-fu has paid off well, it seems. =)
Not sure you’d remember me, but I’m a Patreon supporter and have been a subscriber of yours for a few years now. We’ve exchanged a few emails and some messages on Udemy, and you’ve always been super-helpful and friendly, so hats off to you and your success! =)
And, well, for what it’s worth, I’m going with the hammer this time. Lol!