How Do I Sanitize User Input With Yii 2.0?

In Yii 1.1, there is an extension that is capable of sanitizing user input. Is there a similar built-in feature in Yii 2.0? Else, how do I implement similar feature?

Have you checked the built in \yii\helpers\HtmlPurifier?

HtmlPurifier is not an option to clean simple $_GET variables where you maybe don’t want html at all (why would you want html in a $_GET?), it’s simply too heavy to be used on each request.

You need a light solution for this, either by using strip_tags in conjunction with Html::encode() (which is not always desirable though) or using a xss filter, like the one from CodeIgniter maybe, which can easily be ported to Yii 2.0 with a little effort.

Both strip_tags and CodeIgniter filter proved to be not enough. That’s why HTMLPurifier is there. Yes, it’s slow but at least it’s relatively safe.

Where’s the proof, do you have a link at hand ?

If you’re using whitelist with strip_tags it can hurt you:

Regexp-based sanitizing proved to be fragile:

@samdark - yup, agree with what you’ve posted, these are already known things, especially for the strip_tags() function when you allow tags, things that you should never do.

However, a combination of strip_tags and the xss class on the get vars should be enough since you don’t want html anyway. If you want html, then purify on input with htmlpurifier. I know that some developers prefer to escape at output, but give the memory usage of htmlpurifier, this isn’t really an option if you are also concerned about performance.

Anyway, both points in your posts are valid and should be treated seriously.

Hi Kartik. Thanks for replying. How do I purify all $_POST request with it?

I have tried something like this and it doesn’t work:-

$a = \yii\helpers\HtmlPurifier::process(Yii::$app->request->post());

Any tips on this? Thanks!

HtmlPurifier::process needs a string as a parameter. The $_POST request is an array. You can write a simple global helper function to loop into an array and purify each array element and return the modified array or you can use something like PHP array_map.