When sanitizing the $_POST passed from the controller to the model, I need to sanitize the input and there are 2 options that I can think of.
For the first one, I can nest the if
blocks like this:
if(!empty($username))
{
if(!empty($password))
{
//login the user
}
else
{
echo 'Please enter password.'
}
}
else
{
echo 'Please enter username.'
}
And the other one is like this:
if(empty($username))
{
$err[] = 'Please enter username';
}
if(empty($password))
{
$err[] = 'Please enter password.';
}
if(empty($err)){
//login the user
}
else
{
//display error
}
Which way is the preferred one and is there another, smarter way of sanitizing the input?
-
\$\begingroup\$ These two options — at least the excerpts you have shown us — aren't equivalent. \$\endgroup\$200_success– 200_success2017年09月11日 14:18:20 +00:00Commented Sep 11, 2017 at 14:18
-
\$\begingroup\$ This is just an example. \$\endgroup\$user3628807– user36288072017年09月11日 14:29:27 +00:00Commented Sep 11, 2017 at 14:29
-
1\$\begingroup\$ On Code Review, we review real code, not concepts. See the help center. \$\endgroup\$200_success– 200_success2017年09月11日 14:30:11 +00:00Commented Sep 11, 2017 at 14:30
-
\$\begingroup\$ Ok, I edited my examples. How about now? \$\endgroup\$user3628807– user36288072017年09月11日 14:34:24 +00:00Commented Sep 11, 2017 at 14:34
1 Answer 1
Personally I find if it is a short function, that you do your validation and exit early, these are usually called "guard" clauses
What you are doing here is more what I would call validation, than sanitizing. Eg. sanitizing would be escaping data before feeding it into and sql statement.
$err = [];
if(empty($username))
{
$err[] = 'Please enter username';
}
if(empty($password))
{
$err[] = 'Please enter password.';
}
if(count($err) > 0 ) {
//display error
return;
}
//login the user
-
\$\begingroup\$ What is the difference between
if(count($err) > 0 ) {
andif($err)
\$\endgroup\$user3628807– user36288072017年09月11日 19:53:04 +00:00Commented Sep 11, 2017 at 19:53 -
\$\begingroup\$ Not much really, just because it is an array i use count, it is just out of habbit, what i was really trying to illustrate is splitting that last if/else block, to keep it similar to the if block's you have above it. \$\endgroup\$bumperbox– bumperbox2017年09月11日 20:48:44 +00:00Commented Sep 11, 2017 at 20:48