9-11.Yii2.0框架控制器分配视图并传参xss攻击脚本视图的过滤
[TOC]
一维数组传参
新建控制器:
D:\xampp\htdocs\yii\controllers\HomeController.php
<?php
/**
* Created by Haima.
* Author:Haima
* QQ:228654416
* Date: 2018/8/23
* Time: 5:36
*/
namespace app\controllers;
use yii\base\Controller;
class HomeController extends Controller
{
public function actionIndex()
{
$request = \Yii::$app->request;
if ($request->isGet) {
// 一维数组传方法:
$user = [
'username' => 'lisi1',
'age' => 26,
];
return $this->renderPartial('index', $user); //加载图层,并传参
// return $this->render('index', $data);
}
}
}
新建view模板
D:\xampp\htdocs\yii\views\home\index.php
<?php
/**
* Created by Haima.
* Author:Haima
* QQ:228654416
* Date: 2018/8/23
* Time: 5:43
*/
/* @var $this yii\web\View */
<h2><?=$username?></h2>
效果:
二维数组传参
新建控制器:
D:\xampp\htdocs\yii\controllers\HomeController.php
<?php
/**
* Created by Haima.
* Author:Haima
* QQ:228654416
* Date: 2018/8/23
* Time: 5:36
*/
namespace app\controllers;
use yii\base\Controller;
class HomeController extends Controller
{
public function actionIndex()
{
$request = \Yii::$app->request;
if ($request->isGet) {
$user = [
'username' => 'lisi1',
'age' => 26,
];
$article = [
'title' => 'this is test',
];
// 方法一:构造大数组(二维数组),传参
// $data = [
// 'user' => $user,
// 'article' => $article,
// ];
// return $this->renderPartial('index', $data); //加载图层,并传参
//方法二:用compact()函数构造数组(二维数组)参数,效果同方法一
return $this->renderPartial('index', compact('user', 'article')); //加载图层,并传参
// return $this->render('index', $data);
}
}
}
新建view模板
D:\xampp\htdocs\yii\views\home\index.php
<?php
/**
* Created by Haima.
* Author:Haima
* QQ:228654416
* Date: 2018/8/23
* Time: 5:43
*/
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
<h2><?php echo $user['username']; ?></h2>
<h2><?= $article['title']; ?></h2> <!-- 最简的方式了,yii里没有模板引擎 -->
<h2><?php dump($user);?></h2>
打印效果
视图非法字符的过滤
新建控制器:
D:\xampp\htdocs\yii\controllers\HomeController.php
namespace app\controllers;
use yii\base\Controller;
class HomeController extends Controller
{
public function actionIndex()
{
$request = \Yii::$app->request;
if ($request->isGet) {
// 一维数组传方法:
$user = [
'username' => 'lisi1 <script>alert(132);</script>', //这里模拟传出非法字符串
'age' => 26,
];
return $this->renderPartial('index', $user); //加载图层,并传参
// return $this->render('index', $data);
}
}
}
新建view模板
D:\xampp\htdocs\yii\views\home\index.php
<?php
use \yii\helpers\Html;
use \yii\helpers\HtmlPurifier;
?>
<h2><?=Html::encode($username)?></h2> <!-- 转义特殊字符 -->
<!-- 打印结果: lisi1 <script>alert(132);</script> -->
<h2><?=HtmlPurifier::process($username)?></h2> <!-- 彻底的过滤特殊字符 -->
<!-- 打印结果:lisi1 -->
打印结果:
[Haima的博客]
http://www.cnblogs.com/haima/