views:

772

answers:

2

Hello,

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.

Thanks, Ryan

+2  A: 

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.

Bill Karwin
Thank you both for your straightening me out here. I didn't think about the possibility that the framework does that on its own. Since both of you have 24k reputations, I guess I will take your word for it. :)
ryanulit
@ryanulit: I have 24 reputation. I have no idea where the "k" comes from.
Tomalak
@ryanulit: You don't have to take our word for it. Insert some test data with different levels of escaping applied (be sure to include some special characters for this test), and then query the table and see what was inserted.
Bill Karwin
I just tried it with some sample data and you guys were right. Thanks again.
ryanulit
+1  A: 

The short and simple answer is - if the database access has been abstracted away, there is no need for you to call these functions at all.

The only place where they are needed is if you build actual SQL from bits of strings. Which you should not do anyway, but that's another story.

Bottom line is - the framework will do the right thing, don't interfere.

EDIT: As Bill Karwin points out - htmlspecialchars() is from the completely wrong department here.

Tomalak
Right, but sometimes you have to write SQL by hand, even though you're using an ORM. Not in the case of the OP's question, though.
Bill Karwin
@Bill Karwin: This is why I said "should not do", as opposed to "must not do". It's like running with scissors, which is totally harmless if you know what you're doing. :)
Tomalak