Search code examples
mysqlcakephpmysql-real-escape-stringhtmlspecialchars

What is the best way to use mysql_real_escape_string and htmlspecialchars while saving data in CakePHP?


I am using FCKEditor with CakePHP and when I save data sent from the editor I want to run the htmlspecialchars() and mysql_real_escape_string() functions on the data to clean it before I store it in my database. The problem is I am not really sure where to do this within the CakePHP framework. I tried in the controller like this:

function add() 
{
   if (!empty($this->data)) 
   {
      if ($this->Article->save(mysql_real_escape_string(htmlspecialchars($this->data)))) 
      {
         $this->Session->setFlash('Your article has been saved.');
     $this->redirect(array('action' => 'index'));
      }

   }
}

However $this->data is an array and those functions expect strings so that won't work. Do I do it in the validate array of the model? I have no idea. Also, let me know if running htmlspecialchars() inside of mysql_real_escape_string() is not a good practice.


Solution

  • Don't use htmlspecialchars() when you save data, use it when you output data to HTML. What if you need to look at the data in some context other than HTML?

    Also I'm not a Cake user, but I'd be surprised if you need to apply mysql_real_escape_string() as you save data either. The database access layer should protect you against SQL injection, and by doing it manually you're going to end up storing doubly-escaped strings.