yii2视图参数xss攻击脚本过滤

yii2视图参数xss攻击脚本过滤

class HomeController extends Controller {
    public function actionIndex()
    {
        $data = [
            'str' => 'hello world ',
        ];
        return $this->render('index', $data);  
    }
}

如何让$data数据里的js代码在视图中原样输出?
这里需要用到一个助手类


    echo \yii\helpers\Html::encode($str);    //输出结果:hello world 
?>

为了使用方便一般先引入这个助手类


    use \yii\helpers\Html;
?>

使用

<h1> echo Html::encode($str);?>h1>   //输出结果:hello world <script>alert(1)script>

yii还提供了一个过滤的工具,能够把js等敏感代码完全过滤掉


echo \yii\helpers\HtmlPurifier::process($str);   //输出结果:hello world
?>

为了使用方便一般先引入这个助手类


use \yii\helpers\HtmlPurifier;
?>

使用

<h1> echo HtmlPurifier::process($str);?>h1>

你可能感兴趣的:(yii,yii)