SoFunction
Updated on 2025-03-06

Example of usage of Yii Purifier CHtmlPurifier (Filtering bad code)

This article describes the usage of CHtmlPurifier of Yii purifier. Share it for your reference, as follows:

1. Use in the controller:

public function actionCreate()
{
  $model=new News;
  $purifier = new CHtmlPurifier();
  $purifier->options = array(
    ''=>array(
              'http' => true,
              'https' => true,
    ),
       ''=>'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));
  }
}

2. Use in the model:

protected function beforeSave()
{
  $purifier = new CHtmlPurifier();
  $purifier->options = array(
    ''=>array(
              'http' => true,
              'https' => true,
    ),
       ''=>'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;
  }
}

3. Use in filters:

public function filters()
{
  return array(
    'accessControl', // perform access control for CRUD operations
    'postOnly + delete', // we only allow deletion via POST request
    'purifier + create', //Please perform some filtering operations when loading the insert page  );
}
public function filterPurifier($filterChain){
  $purifier = new CHtmlPurifier();
  $purifier->options = array(
    ''=>array(
              'http' => true,
              'https' => true,
    ),
       ''=>'div',
  );
  if(isset($_POST['news']){
    $_POST['news']['content'] = $purify($_POST['news']['content']);
  }
    $filterChain->run();
}

4. Use in the view:

<?php $this->beginWidget('CHtmlPurifier'); ?>
...display user-entered content here...
<?php $this->endWidget(); ?>

For more information about Yii, readers who are interested in this site can view the topic:Yii framework introduction and common techniques summary》、《Summary of excellent development framework for php》、《Basic tutorial on getting started with smarty templates》、《PHP object-oriented programming tutorial》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.