视图参数xss攻击脚本过滤
class HomeController extends Controller { public function actionIndex() { $data = [ 'str' => 'hello world <script>alert(1)</script>', ]; return $this->render('index', $data); } }
如何让$data数据里的js代码在视图中原样输出?
这里需要用到一个助手类
<?php echo \yii\helpers\Html::encode($str); //输出结果:hello world <script>alert(1)</script> ?>
为了使用方便一般先引入这个助手类
<?php use \yii\helpers\Html; ?>
使用
<h1><?php echo Html::encode($str);?></h1> //输出结果:hello world <script>alert(1)</script>
yii还提供了一个过滤的工具,能够把js等敏感代码完全过滤掉
<?php echo \yii\helpers\HtmlPurifier::process($str); //输出结果:hello world ?>
为了使用方便一般先引入这个助手类
<?php use \yii\helpers\HtmlPurifier; ?>
使用
<h1><?php echo HtmlPurifier::process($str);?></h1>