Jump to content

Validate Before Or After Sanitizing


MIPS64

Recommended Posts

Does it matter if I validate the post variables before or after I sanitize?

 

So sanitize first (using prepared statements so no mysql_real_escape_string)?

 


if (isset($_POST['submit'])) {

  $username = trim(htmlspecialchars($_POST['username]));

  if (strlen($username) < 3) {
  echo 'Username must be at least 3 characters';
  }

  insert data next

 

or

 


if (isset($_POST['submit'])) {

  if (strlen($_POST['username']) < 3) {
  echo 'Username must be at least 3 characters';
  }

 $username = trim(htmlspecialchars($_POST['username]));

 insert data next

Link to comment
Share on other sites

You sanitise just before you use it in your queries.

If it's invalid there's no point in even using it.

Ergo, validate first.

 

+1

 

To expand on Barands' response let me provide an illustration of why you should validate first.

 

Let's say you have a field where you want to enforce a minimum character length of 6. If the user inputs "o'kay" (5 characters) and you sanitize first (using mysql_real_escape_string() or something similar), the value will pass the validation because the apostrophe will be escaped and the result will be "o\'kay" (6 characters). By the same token, if you have a field where you want to allow an apostrophe but not the backslash, sanitizing first can result in a valid input being rejected.

Link to comment
Share on other sites

That's more verification than validation, as with validation you just want to make sure that the input conforms to the acceptable pattern. So validation should/must happen before the data is used in any way, including verification against other data.

 

Other than that, it's a good point: Never forget about output escaping. ;)

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.