Automatically purify input

Hey Guys,

while reading the Security-Section on I came across the question, if I automatically can use CHtmlPurifier to validate user input?

Using CHtmlPurifier directly in the view file is according to the performance not that good and so it would be great to use it before, so that malicious input gets not saved in the database.

Can anyone help me?


As was said in the guide, you can use your custom filter in rules. Other than that you can always loop through the $_POST\$_GET

public function rules()



		return array(

                     array('name, position, address, icq, misc', 'filter', 'filter'=> array($this, 'purify')), 



      public function purify($value){

            return  strip_tags($value);


Yes, but incendium wanted to use CHtmlPurifier ;)

Read this: (the last line)

array('text','filter','filter'=>array($obj=new CHtmlPurifier(),'purify')),

If you’ll add this validator (which is not actually a validator) to your model then the “text” field will be purified and inserted into a database without malicious code.

Hi guys!

Just as I believe the OP is looking for a "catch all" solution to this, so am I.

While the provided method is great for sanitizing single input fields (like the ‘text’ field in the above case), why not automatically purify ALL inputs? After all, client input is not to be trusted!

Can we use filters for this purpose? If so, how is it done? (Documentation on filters is a bit thin…)

If not, is there another solution?

It would be a bit difficult to implement a content management system with that approach. Sometimes you want to keep html tags in user input.

You can write - for example - a model behavior that automatically purifies all attributes in beforeValidate() or beforeSave() method.

True, but then I would have to manually iterate through the fields. Using the validator, albeit a bit ad hoc, is perhaps a cleaner way. I still have a feeling that using filters might be the best solution (for me), but I still don’t fully grasp how they work, yet…

Edit: I read up on behaviours. That might be the way to go. Thanks!