WordPress Code Snippets

A fresh mix of code snippets and tutorials

PHP Sanitize XSS

246

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.

This function does two things to sanitize the input $value and protect against XSS:

  1. Removes all PHP and HTML tags via strip_tags()
  2. 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 ;)


Show Support

Like our new Facebook Page to show support!