Simple PHP XSS injection preventer

DISCLAIMER: This post is really old. There are better ways to prevent XSS injection nowadays.

I’m using the following snippet to avoid XSS injection through forms. It’s simple. I’ve already seen some more advanced techniques to do this, but for some cases, it’s enough.

If you have form fields that allow HTML tags, you probably want to ignore (or at least filter) its content.

$basePath = '/path_to_scripts';

// Here comes the fields that can have HTML tags. You can add
// how many scripts and fields you want.
$allowhtml = array( '/myscript.php' => array( 'editor' ) );

// Allowed tags.
$tags = '<h1><h2><h3><h4><h5><h6><p><span><strong><b><em><i>'
    . '<address><pre><blockquote><ol><ul><li><a><br>';

// If your scripts are not on the root directory of your
// website you may clean the URI.
$uri = str_replace($basePath, '',
    strstr($_SERVER['REQUEST_URI'], $basePath));

// And, the filter begins...
$fields = array();
if (isset($allowhtml[$uri])) {
  $fields = $allowhtml[$uri];

// You may use $_REQUEST instead two loops with $_GET and $_POST
foreach ($_GET as $k => $v) {
  $_GET[$k] = strip_tags($v, in_array($k, $fields) ? $tags : '');
foreach ($_POST as $k => $v) {
  $_POST[$k] = strip_tags($v, in_array($k, $fields) ? $tags : '');

Do you have some other way  to prevent XSS injection? Share your experiences using the comment form bellow.


One thought on “Simple PHP XSS injection preventer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

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