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
https://forums.phpfreaks.com/topic/270174-validate-before-or-after-sanitizing/
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.

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. ;)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.