Sanitize Your Data Easily

Posted by Jeremy Harris on Tue, Oct 05, 2010 @ 11:15pm

When you're dealing with a lot of user submitted data, it's important to sanitize it. CakePHP provides a Sanitizer class that provides much of the functionality you need to deal with unclean data, but it can be a pain iterating through your data before saving it.

Enter Sanitizer

The Sanitizer plugin automatically sanitizes your data based on a set of rules you define on the model, similar to how you would define validation rules. First, include the Sanitizer behavior:

var $actsAs = array('Sanitizer.Sanitize');

Like validation, the Sanitize behavior looks at your data on a per-field basis. To define rules, pass the field name as the key and the sanitization rule (based on Cake's Sanitize class) as the value.

// clean the name field using Sanitize::html()
var $sanitize = array(
    'name' => 'html'
);

The above rule will sanitize the name field using Sanitize::html(). By default, Sanitizer uses the very strict Sanitize::clean($value, array('remove_html' => true)); to clean your data.

There are other options available on the plugin, such as skipping fields or a model entirely. You can also sanitize using different methods on the Sanitize class as well as pass variables you would normally pass to them.

// or clean the name field using Sanitize::paranoid() and allowing '%'
var $sanitize = array(
    'name' => array(
        'paranoid => array('%')
    )
);

For more information, read the readme and check out the tests.

Download

Download the Sanitizer plugin here.