0
\$\begingroup\$

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?

asked Sep 11, 2017 at 14:16
\$\endgroup\$
4
  • \$\begingroup\$ These two options — at least the excerpts you have shown us — aren't equivalent. \$\endgroup\$ Commented Sep 11, 2017 at 14:18
  • \$\begingroup\$ This is just an example. \$\endgroup\$ Commented Sep 11, 2017 at 14:29
  • 1
    \$\begingroup\$ On Code Review, we review real code, not concepts. See the help center. \$\endgroup\$ Commented Sep 11, 2017 at 14:30
  • \$\begingroup\$ Ok, I edited my examples. How about now? \$\endgroup\$ Commented Sep 11, 2017 at 14:34

1 Answer 1

2
\$\begingroup\$

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
answered Sep 11, 2017 at 19:43
\$\endgroup\$
2
  • \$\begingroup\$ What is the difference between if(count($err) > 0 ) { and if($err) \$\endgroup\$ Commented 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\$ Commented Sep 11, 2017 at 20:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.