Here’s how to prevent XSS attacks by escaping output in PHP:
[evd_youtube video_id=”pc0V9hJpE54″ playlist_id=”PLrG78JjvL7hWah18gU57tCtbFOvsxl9pp”]
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.
That code would be stored in the database, output to the page when loaded, and because it’s not escaped… render and run.
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.