Yii CHtmlPurifier 净化器概述
本例详细解析了Yii框架中CHtmlPurifier净化器的实际应用方法,旨在为开发者提供可参考的代码实现。
首先介绍如何在控制器的动作方法中调用该组件进行数据清洗。
public function actionCreate()
{
$model=new News;
$purifier = new CHtmlPurifier();
$purifier->options = array(
'URI.AllowedSchemes'=>array(
'http' => true,
'https' => true,
),
'HTML.Allowed'=>'div',
);
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$model->attributes['content'] = $purifier->purify($model->attributes['content']);
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
}
其次展示在模型层利用生命周期钩子自动执行净化逻辑的方式。
protected function beforeSave()
{
$purifier = new CHtmlPurifier();
$purifier->options = array(
'URI.AllowedSchemes'=>array(
'http' => true,
'https' => true,
),
'HTML.Allowed'=>'div',
);
if(parent::beforeSave()){
if($this->isNewRecord){
$this->create_data = date('y-m-d H:m:s');
$this->content = $purifier->purify($this->content);
}
return true;
}else{
return false;
}
}
接着说明如何通过定义过滤器来拦截特定操作并实施过滤。
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
'purifier + create', //载入插入页面时进行些过滤操作
);
}
public function filterPurifier($filterChain){
$purifier = new CHtmlPurifier();
$purifier->options = array(
'URI.AllowedSchemes'=>array(
'http' => true,
'https' => true,
),
'HTML.Allowed'=>'div',
);
if(isset($_POST['news']){
$_POST['news']['content'] = $purify($_POST['news']['content']);
}
$filterChain->run();
}
最后提及在视图层渲染用户提交内容时的注意事项及展示方式。
<?php $this->beginWidget('CHtmlPurifier'); ?>
...display user-entered content here...
<?php $this->endWidget(); ?>
期望上述关于基于Yii框架的PHP程序设计中的净化器应用技巧,能对读者有所帮助。