完整的php对用户输入进行过滤特殊字符的函数

不要相信任何用户的任何输入,用户的输入总是有意无意地对我们的程序产生bug,所以我们需要做一些基本的防备。

其实我们php是后端语言,对前端的数据进行处理,最后进行逻辑实现或者存储。


只靠前端判断,后端直接用是不可靠的,小人难防,意外难猜~。

只靠后端判断效率太低,每次都要后端反馈回来,造成不必要的资源浪费,请求不合理。

所以最好就是前端和后端同时验证,前端保证效率、后端防小人~

基本思路:前端页面判断=》后端判断=》最终操作。

说了那么多,其实就是说一个替换函数啦,当然可以直接用正则表达式进行替换过滤,据说正则比较消耗资源(没实测)~


下面是一个常用的函数,用来过滤特殊字符,防止sql注入、跨站攻击、js攻击等。其实,最好还是直接把特殊字符防止一个数组里面,一次性调用,不用多次去除。

/**
     * @param $str
     * @return string 过滤后的返回字符串
     *  常常用在客户之间输入的地方,比如留言板、资料填写等
     */
    function strFilter($str)
    {
        $str = str_replace('`', '', $str);
        $str = str_replace('·', '', $str);
        $str = str_replace('~', '', $str);
        $str = str_replace('!', '', $str);
        $str = str_replace('!', '', $str);
        $str = str_replace('@', '', $str);
        $str = str_replace('#', '', $str);
        $str = str_replace('$', '', $str);
        $str = str_replace('¥', '', $str);
        $str = str_replace('%', '', $str);
        $str = str_replace('^', '', $str);
        $str = str_replace('……', '', $str);
        $str = str_replace('&', '', $str);
        $str = str_replace('*', '', $str);
        $str = str_replace('(', '', $str);
        $str = str_replace(')', '', $str);
        $str = str_replace('(', '', $str);
        $str = str_replace(')', '', $str);
        $str = str_replace('-', '', $str);
        $str = str_replace('_', '', $str);
        $str = str_replace('——', '', $str);
        $str = str_replace('+', '', $str);
        $str = str_replace('=', '', $str);
        $str = str_replace('|', '', $str);
        $str = str_replace('\\', '', $str);
        $str = str_replace('[', '', $str);
        $str = str_replace(']', '', $str);
        $str = str_replace('【', '', $str);
        $str = str_replace('】', '', $str);
        $str = str_replace('{', '', $str);
        $str = str_replace('}', '', $str);
        $str = str_replace(';', '', $str);
        $str = str_replace(';', '', $str);
        $str = str_replace(':', '', $str);
        $str = str_replace(':', '', $str);
        $str = str_replace('\'', '', $str);
        $str = str_replace('"', '', $str);
        $str = str_replace('“', '', $str);
        $str = str_replace('”', '', $str);
        $str = str_replace(',', '', $str);
        $str = str_replace(',', '', $str);
        $str = str_replace('<', '', $str);
        $str = str_replace('>', '', $str);
        $str = str_replace('《', '', $str);
        $str = str_replace('》', '', $str);
        $str = str_replace('.', '', $str);
        $str = str_replace('。', '', $str);
        $str = str_replace('/', '', $str);
        $str = str_replace('、', '', $str);
        $str = str_replace('?', '', $str);
        $str = str_replace('?', '', $str);
        return trim($str);
    }




评论/留言