1

This is my first participation is this great website, so I hope to get the first great answer to my question. I'm using the following code to insert data into MySQL database:

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form2")) 
{
$q = $conn->prepare("INSERT INTO client (name, address) VALUES (:name, :address)");
$q->bindValue(':name', htmlspecialchars($_POST['name']), PDO::PARAM_STR);
$q->bindValue(':address', htmlspecialchars($_POST['address']), PDO::PARAM_STR);
$q->execute();
}

Is the insertion secure enough? Should I use htmlspecialchars() the moment of insertion or rhe moment of displaying data?

Kind regards

MrCode
  • 63,975
  • 10
  • 90
  • 112
Anibel
  • 175
  • 1
  • 3
  • 14
  • I am always cautious of security so would strip the input. You are inserting directly into a database from a form here, so it is probably a good idea to vet the input. – dwjv Oct 04 '13 at 14:34
  • @dwjv I'm pretty sure without checking if the value isset() first, you'll get a notice error. There's nothing wrong with making sure a value is set, along with making sure it's the right value. – Sterling Archer Oct 04 '13 at 14:37
  • 1
    See http://stackoverflow.com/a/60496/760211 , that PDO MySQL driver's default setting is __emulating prepared statement__. You may want to disable the ``emulation`` for better security. – Kita Oct 04 '13 at 14:39
  • @RUJordan Yeah, I had two pints at lunch and wasn't thinking straight, you're totally right. You noticed before I had a chance to edit my comment. – dwjv Oct 04 '13 at 14:40
  • 1
    This is indeed a "great question" as it is asked every week on a regular basis. – Your Common Sense Oct 04 '13 at 15:21

1 Answers1

3

Yes your code is secure but as a general rule of thumb, store data in a neutral form. That is, not encoded for any specific output or medium. Do the encoding on the way out not in.

If you were to do the opposite and pass it through htmlspecialchars() before storing (like your code in the question), then your data is tied specifically to be output in HTML. If you wanted to output it elsewhere (such as an XML document for example), where htmlspecialchars() is not applicable, then you would have to first decode it.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Yes! `htmlspecialchars` is for *display* formatting, not encoding for storage. It should be called when the content needs to be rendered. – tadman Oct 04 '13 at 14:49
  • Thanks a lot for the reply, but could you tell me what do you mean exactly by "neutral form"? In addition, what do you suggest? how can I change the code above? – Anibel Oct 04 '13 at 14:49
  • By neutral form I mean just in raw form (without any processing from `htmlspecialchars()`). I would just remove the `htmlspecialchars()` call from your code and leave it as is. Don't forget to do the `htmlspecialchars()` call when you pull out the data and display it in HTML. – MrCode Oct 04 '13 at 15:35