Home > PHP Framework > YII > body text

How to prevent xss attacks in yii2

藏色散人
Release: 2020-07-20 09:55:48
Original
3733 people have browsed it

yii2防止xss攻击的方法:首先定义一个用于防xss攻击的“actionClean”方法;然后在方法体内实现去除特殊字符;最后调用该方法即可。

How to prevent xss attacks in yii2

PHP中常用到的方法有:

推荐:《yii教程

 /*  防sql注入,xss攻击  (1)*/
    function actionClean($str)
    {
        $str=trim($str);
        $str=strip_tags($str);
        $str=stripslashes($str);
        $str=addslashes($str);
        $str=rawurldecode($str);
        $str=quotemeta($str);
        $str=htmlspecialchars($str);
        //去除特殊字符
        $str=preg_replace("/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\&#39;|\`|\-|\=|\\\|\|/", "" , $str);
        $str=preg_replace("/\s/", "", $str);//去除空格、换行符、制表符
        return $str;
    }


    //防止sql注入。xss攻击(1)
    public function actionFilterArr($arr)
    {
        if(is_array($arr)){
            foreach($arr as $k => $v){
                $arr[$k] = $this->actionFilterWords($v);
            }
        }else{
            $arr = $this->actionFilterWords($arr);
        }
        return $arr;
    }


    //防止xss攻击
   public function actionFilterWords($str)
    {
        $farr = array(
            "/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU",
            "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
            "/select|insert|update|delete|drop|\&#39;|\/\*|\*|\+|\-|\"|\.\.\/|\.\/|union|into|load_file|outfile|dump/is"
        );
        $str = preg_replace($farr,&#39;&#39;,$str);
        return $str;
    }

    //防止sql注入,xss攻击(2)
    public function post_check($post) {
      if(!get_magic_quotes_gpc()) {
          foreach($post as $key=>$val){
             $post[$key]  = addslashes($val);
          }
        }
      foreach($post as $key=>$val){
        //把"_"过滤掉
        $post[$key] = str_replace("_", "\_", $val);
        //把"%"过滤掉
        $post[$key] = str_replace("%", "\%", $val); //sql注入
        $post[$key] = nl2br($val);
        //转换html
        $post[$key] = htmlspecialchars($val); //xss攻击
      }
      return $post;
  }
Copy after login

调用:

 

(必须放在接收数据之外)

注意:

表单提交值,为防止csrf攻击,控制器中需要加上:

The above is the detailed content of How to prevent xss attacks in yii2. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!