-1

I'm trying to create a function which would delete any potentional script tags, but not other tags like p, li, ol, span, h1, ...

This is what I have so far. I also wrote < and > as encoded chars "%3C" and "%3E" and as HTML name and number. Tried to do regex for first one as you see "^<(/)?script>$". But it's not working :D

function smartFilter($string) {
    $string = strtolower($string);
    if (strpos($string, "<script>") !== FALSE || strpos($string, "&#60;script&#62;") !== FALSE || strpos($string, "&lt;script&gt;") !== FALSE || strpos($string, "%3Cscript%3E") !== FALSE) {
        $unallowed = array("^<(\/)?script>$", "&lt;script&gt;", "&lt;/script&gt;", "%3Cscript%3E", "%3C/script%3E", "&#60;script&#62;", "&#60;script&#62;");
        return preg_replace($unallowed, "", $string);
    } else {
        return $string;
    }
}
  • At its most basic you should use `strip_tags()` but if you want this really secure you should probably look for a 3rd party library that does it even better. – developerwjk Feb 10 '15 at 21:01
  • As far as I know strip_tags removes all tags. But I don't want that because i have rich textbox editor and user can input headings and stuff like that but I don't want them to insert JS codes – IEMSlovenia Feb 10 '15 at 21:02
  • 2
    Did you read the docs? You can list allowable tags in the function. – developerwjk Feb 10 '15 at 21:03
  • @developerwjk Whilst PHP's `strip_tags()` can remove the actual ` – MrWhite Feb 10 '15 at 21:07
  • Yeah I feel embarrassed. Using IDE which don't support documentation on the fly nor did I check the manual for strip_tags.It's working:) – IEMSlovenia Feb 10 '15 at 21:10

2 Answers2

0

Why not use strip_tags from php? Link here.

  • Unfortunately `strip_tags()` cannot be used to remove the entire `script` element. It literally only removes the tags and leaves its content. It's "safe", but probably not desirable. ` – MrWhite Feb 10 '15 at 21:11
  • Yeah well I don't mind for the code left :D I Will at least know who want's to hack me and how he want's to hack me :D – IEMSlovenia Feb 10 '15 at 21:14
  • 1
    If you'd like more complex and rock solid solution I would recommend http://htmlpurifier.org/. – Łukasz Wojciechowski Feb 10 '15 at 21:17
0

This did all the work I asked for :D

function smartFilter($string) {
    return strip_tags($string, "<p><li><ol><ul><h1><h2><h3><h4><h5><span><b><u><i>");
}
  • 1
    Note that JS can still be embedded inline in the tags that you allow. `strip_tags()` is only really intended for controlled content, not user-submitted content. – MrWhite Feb 10 '15 at 21:19