Compression

Compression is a light weight class that will load a CSS stylesheet, bind and translate given variables, compress and remove white space and cache the output for future use.

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.

/**
 * 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;
}
Related Entries:

3 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]
  • thedilab
    the-di-lab.com
    Jul 31st 2009, 09:55
    1 happend to see you website by chance,
    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
  • Lucas Costa
    Jun 1st 2010, 12:49
    2 Miles, thanks for this code.

    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
  • hendra
    Jun 27th 2011, 20:54
    3 help me

    error :
    Undefined property: AppModel::$cleanData

    how do i do ?