27 posts
  • Trendsetter
  • Weekly Top Seller
  • Author Level 6
  • Collector Level 4
+2 more

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.