Stripping HTML automatically from your data
This article is over a year old and may contain outdated information.
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.
/**
* Strip all html tags from an array
*
* @param array $data
* @return array
*/
public 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 AppModel::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
error :
Undefined property: AppModel::$cleanData
how do i do ?
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
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