Skip to content
Advertisement

server side data validation with nesting

I cannot figure out why my nesting here is not working. Whenever I run this it goes straight to ‘Incorrect password’ (with all the fields blank) even though the condition about string length that proceeds it, is false. A reading of ‘Email and password are required’ is what I want to happen first. THEN if the email doesn’t contain an @ sign, the @ notification, THEN the password notification. But it keeps jumping over my previous if statements. I know the nesting must be wrong, and I’ve re-arranged it many times. The only way it works is to remove the @ verification line completely, but I need to have it.

if ( isset($_POST['who']) && isset($_POST['pass']) ) {

    if ( strlen($_POST['who']) < 1 || strlen($_POST['pass']) < 1 ) {
       $failure = "E-mail and password are required"; 
    }
    if(stripos($_POST['who'],'@') === false && strlen($_POST['who'] > 1)) {
        $failure = "E-mail must have an at-sign (@)";
    }

    else {
       $check = hash('md5', $salt.$_POST['pass']);
          if ( $check == $stored_hash ) {
          // Redirect the browser to auto.php
          header("Location: auto.php?name=".urlencode($_POST['who']));
          return;
          } else {
          $failure = "Incorrect password";
          }
    }
} 

Advertisement

Answer

you need to put 2nd if condition in else block. think about when password was blank but email was entered. it will bypass 2nd if block and go to else use like blow code

if ( isset($_POST['who']) && isset($_POST['pass']) ) {

 if ( strlen($_POST['who']) <= 1 || strlen($_POST['pass']) < 1 ) {
   $failure = "E-mail and password are required"; 
 } 
 else { 
  if(stripos($_POST['who'],'@') === false && strlen($_POST['who'] > 1)) {
     $failure = "E-mail must have an at-sign (@)";
  }

  else {
     $check = hash('md5', $salt.$_POST['pass']);
      if ( $check == $stored_hash ) {
        // Redirect the browser to auto.php
        header("Location: auto.php?name=".urlencode($_POST['who']));
        return;
      } else {
        $failure = "Incorrect password";
      }
  }
 }
} 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement