June 18, 2015

Prevent XSS Attacks. Escape Strings in PHP

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.