27 posts
  • Has referred 1+ members
  • Has sold $10,000+ on Envato Market
  • Has collected 100+ items on Envato Market
  • Sells items exclusively on Envato Market
+2 more
incrediblebytes says

Hi :) i was doing a small PHP app recently and just want to share a simple solution for preventing XSS attacks while still allowing some HTML . This can be useful for beginners and intermediate PHP users.

This is the code:


function simpleFilter($mixed, $encoding, $except = array()) {
    if (is_array($mixed)) {
        foreach($mixed as $key => $value) {
            if (!in_array($key, $except, true)) {
                if (is_array($value)) $mixed[$key] = simpleFilter($value, $encoding, $except);
                else $mixed[$key] = htmlspecialchars($value, ENT_NOQUOTES, $encoding);
            }
        }
    }
    else $mixed = htmlspecialchars($mixed, ENT_NOQUOTES, $encoding);
    return $mixed;
}

function filterSome($value, $encoding) {
    $value = htmlspecialchars($value, ENT_NOQUOTES, $encoding);
    $value = preg_replace('/&lt;img (src="[a-zA-Z0-9\-._ ]+.(jpg|jpeg|png|gif){1}"){1}( alt="(.*)")? \/&gt;/u', '<img \\1\\3 />', $value);
    $value = preg_replace('/&lt;(\/)*p&gt;/u', '<\\1p>', $value);
    $value = preg_replace('/&lt;(\/)*h2&gt;/u', '<\\1h2>', $value);
    $value = preg_replace('/&lt;a href=(\'|")*([^\'"]+)(\'|")*&gt;(.+)&lt;\/a&gt;/u', '<a href="\\2">\\4</a>', $value); 
    return $value;
}

Function simpleFilter simply filters input array or string with htmlspecialchars command, while the second one not only filters the input with htmlspecialchars() but also adds some HTML white list and can simply be extended with some other regular expressions when needed. To improve performance such functions must be used before you insert user’s input into database, or at some exceptions.

If you have some suggestions or improvements or a different way please leave a comment.

Helpful Information

  • Please read our community guidelines. Self promotion and discussion of piracy is not allowed.
  • Open a support ticket if you would like specific help with your account, deposits or purchases.
  • Item Support by authors is optional and may vary. Please see the Support tab on each item page.

Most of all, enjoy your time here. Thank you for being a valued Envato community member.

Post Reply

Format your entry with some basic HTML. Read the Full Details, or here is a refresher:

<strong></strong> to make things bold
<em></em> to emphasize
<ul><li> or <ol><li> to make lists
<h3> or <h4> to make headings
<pre></pre> for code blocks
<code></code> for a few words of code
<a></a> for links
<img> to paste in an image (it'll need to be hosted somewhere else though)
<blockquote></blockquote> to quote somebody

:grin: :shocked: :cry: Complete List of Smiley Codes

by
by
by
by
by
by