XSS safe model content

In this post I am going to describe a solution to make your yii-based web application safe from illegal content injections.

I am going to make a use of the the yii wrapped htmlpurifier class inside a behavior. this behavior could be attached to any model with declaring the attributes we would like to make them XSS safe.

I have wrote the following behavior :

class CSafeContentBehavior extends CActiveRecordBehavior
{
    public $attributes =array();
    protected $purifier;
 
    function __construct(){
        $this->purifier = new CHtmlPurifier;
    }
 
    public function beforeSave($event)
    {
        foreach($this->attributes as $attribute){
            $this->getOwner()->{$attribute} = $this->purifier->purify($this->getOwner()->{$attribute});
        }
    }
}

place this class in a file in your application directory, for example : application/behaviors/CSafeContentBehavior.php Now in your model you attach the behavior like this :

class Post extends CActiveRecord
{
 
public function behaviors(){
    return array(
        'CSafeContentBehavor' => array( 
            'class' => 'application.behaviors.CSafeContentBehavior',
            'attributes' => array('title', 'body'),
        ),
    );
}

Here we go. Our Post model will now purify title and body columns before each save operation.

Total 3 comments:

#1170
Performance issue
by samdark at 2:36am on February 25, 2010.

CHtmlPurifier will be initialized every on model creation. Right?

#1173
2sam
by someone at 2:49am on February 25, 2010.

seems to be samdark is right

#1176
Another implementation
by fduch at 2:39am on February 26, 2010.

I think that this part "'attributes' => array('title', 'body')," better to implement as validator (similar as new CSafeValidator). To define behaviors for column in one place.

Your Comment:

You may enter comment using Markdown syntax.

Please login with your forum account.
Note: you must have at least ONE forum post with your account.