Resession

A small lightweight script that can manage and manipulate Session data.

Automatically sanitizing data with beforeSave()

Tuesday, July 14th 2009, 1:49am
Topics: Tutorials, CakePHP
Tags: Model, Data, Sanitize, Clean, Automatically, beforeSave
Comments: 2
Permalink - Tinylink

So if you are like me and hate having to sanitize or clean your data manually within each action, and was hoping there was an easier way, there is. Simple combine the magic of the Models beforeSave() and the powerful strength of Sanitize::clean().

function beforeSave() {
	if (!empty($this->data) && $this->cleanData === true) {
		$connection = (!empty($this->useDbConfig)) ? $this->useDbConfig : 'default';
		
		$this->data = Sanitize::clean($this->data, array('connection' => $connection, 'escape' => false));
	}
	
	return true;
}


The previous code will attempt to clean all data before it is saved. Secondly it will convert HTML, it will not strip tags completely. So if you do not want HTML in your database, you will need to add some extra functionality and set encode to false in the clean() options.

But that's not it, were not finished just yet. You may have noticed a $cleanData variable and are probably wondering what it does. This is a custom property that should be placed in your AppModel and IS NOT a CakePHP property. By placing it in the AppModel we will receive no error notices and all data will be cleaned, additionally you can disable cleaning in certain models by setting the property to false in the respective model.

var $cleanData = true;


Known Errors
So far this has worked smoothly, except for the following exception:

- Serialized arrays will be escaped incorrectly and will break when trying to unserialize(), simply set $cleanData to false to not escape the serialized arrays.

- When escape is set to true, all data will have slashes added on top of the slashes already added with the Model class, so its best to turn escaping off
Related Entries:

2 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]
  • Akif
    Jul 15th 2009, 09:04
    1 Nice articles. Keep up the good work.

    I have a question on this articles though. You are talking about cleaning the data array? What are you clearing exactly?

    (Never new it was dirty :P)
  • Stefan
    wiegreffe.de
    Jul 29th 2009, 06:55
    2 Hi there. Although I enjoy most of your articles, I have a serious issue with this one. The problem: clean sanitizes date fields, converting the hyphens in 2009-07-29 to 2009-07-29 which results in not being able to save all kinds of dates, including the autmagically filled fields 'created' and 'modified'.

    Any suggestions on this one?