Stripping HTML automatically from your data
Monday, July 20th 2009, 11:38pm
Topics: Tutorials, CakePHP
Tags: Model, Data, Sanitize, Clean, Automatically, beforeSave, Strip, HTML
Comments: 3
Permalink -
Tinylink
About a week ago I talked about automatically sanitizing your data before its saved. Now I want to talk about automatically stripping HTML from your data before its saved, which is good practice. Personally, I hate saving any type of HTML to a database, thats why I prefer a BB code type system for this website. To strip all tags from your data, add this method to your AppModel.
Pretty simple right? The next and final step is to add it to your AppModel's beforeSave(). In the next example, I will use the code snippet from my previous related article. Once you have done this your are finished, now go give it a test drive.
/**
* Strip all html tags from an array
* @param array $data
* @return array
*/
function cleanHtml($data) {
if (is_array($data)) {
foreach ($data as $key => $var) {
$data[$key] = $this->cleanHtml($var);
}
} else {
$data = Sanitize::html($data, true);
}
return $data;
}Pretty simple right? The next and final step is to add it to your AppModel's beforeSave(). In the next example, I will use the code snippet from my previous related article. Once you have done this your are finished, now go give it a test drive.
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));
$this->data = $this->cleanHtml($this->data);
}
return true;
}
3 Comments
the-di-lab.com
Jul 31st 2009, 09:55
very active site and useful posting.
This is my site www.the-di-lab.com anyways,
hope to see you there and communicate all thoughts about Jquery and Cakephp.
Regards.
thedilab
Jun 1st 2010, 12:49
I've updated the line $data = Sanitize::html($data, true); to if(!is_null($data)) $data = Sanitize::html($data, true);.
Otherwise null data gets converted to string on sanitization and goes to the db as ''.
Best regards
Jun 27th 2011, 20:54
error :
Undefined property: AppModel::$cleanData
how do i do ?