html中出现的script失效

时间:2023-03-08 19:25:00

如果在Controller中出现script代码类似

$hello_str='Hello God<script>alert(3);</script>';

那么我不希望在传给view的时候出现弹框,那么就在view文件中使用

use yii\helpers\Html;

并且输出时使用 Html::encode

<?=Html::encode($view_hello_str);?>

还有一种方法就是过滤调script代码:

use yii\helpers\HtmlPurifier;

然后:

<?=HtmlPurifier::process($view_hello_str);?>

输出时只有 Hello God

使用该方法的目的是为了防止用户恶意传入参数