PHP Sanitize XSS
Here is a simple PHP function I use to prevent XSS attacks. Use it to sanitize any user-input or otherwise unknown variables before use.
function sanitize_xss($value) {
return htmlspecialchars(strip_tags($value));
}
This function does two things to sanitize the input $value
and protect against XSS:
- Removes all PHP and HTML tags via strip_tags()
- Converts all special characters to their HTML-entity equivalents via tmlspecialchars()
When combined, these two functions eliminate any chance of a successful XSS attack. All tags are removed and all quotes and other special characters are encoded. So yeah, XSS is not gonna happen when using the sanitize_xss()
function provided above.
Example
For those who may be new to PHP, here is an example of how this function would be used. Let’s say that you have a variable named $user_input
that you want to sanitize before echoing to the browser. All you need to do is:
<?php echo sanitize_xss($user_input); ?>
..and kiss XSS goodbye ;)