php过滤onclick等类似xss代码

php过滤onclick等类似xss代码

php过滤onclick等类似xss代码

xss跨站脚本攻击很平常,新手在开发网站的时候很容易犯这个错,那么今天我们利用正则来过滤掉一些危险的js脚本

比如onclick事件、onerr、onload等类似事件,甚至在href中的javascript事件都需要过滤掉,php代码如下

    public function filterBadHtml($str)
    {
        $str = preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si", "", $str); // 过滤script标签
        $str = preg_replace("/<(\/?script.*?)>/si", "", $str); // 过滤script标签
        $str = preg_replace("/javascript\s*(:)+/si", "BfwJavascript", $str); // 过滤href script标签
        $str = preg_replace("/vbscript\s*(:)+/si", "BfwVbscript", $str); // 过滤href script标签
        $str = preg_replace("/\s+on([a-z]+)\s*=/si", "BfwOn\\1=", $str); // 过滤on script标签
        return $str;
    }

亲测可用,大家可以试试


{{collectdata}}

网友评论0