Got the code below for a login form to check that users dont miss a field and then to check wether or not the data user and pass fields match what is in the database but i cant seem to structure my if, elseif, else statements correctly

<?php
/**
 * Checks to see if the user has submitted his
 * username and password through the login form,
 * if so, checks authenticity in database and
 * creates session.
 */

if(isset($_POST['sublogin'])){
   
   $_POST['user'] = trim($_POST['user']);
	
   /* Check that all fields were typed in */
   if(!$_POST['user'] || !$_POST['pass']){
      echo "<p>Missed a field</p>";
   }
   
   elseif(strlen($_POST['user']) > 30){
      echo "<p>Sorry too long</p>";
   }  
   
/* Checks that username is in database and password is correct */
   $md5pass = md5($_POST['pass']);
   $result = confirmUser($_POST['user'], $md5pass);

   /* Check error codes */
   elseif($result == 1){
      die('That username doesn\'t exist in our database.');
   }
   elseif($result == 2){
      die('Incorrect password, please try again.');
   }

	else{
   /* Username and password correct, register session variables */
   $_POST['user'] = stripslashes($_POST['user']);
   $_SESSION['username'] = $_POST['user'];
   $_SESSION['password'] = $md5pass;

   /**
    * This is the cool part: the user has requested that we remember that
    * he's logged in, so we set two cookies. One to hold his username,
    * and one to hold his md5 encrypted password. We set them both to
    * expire in 100 days. Now, next time he comes to our site, we will
    * log him in automatically.
    */
   if(isset($_POST['remember'])){
      setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/");
      setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
   }
	}

   /* Quick self-redirect to avoid resending data on refresh */
   echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[PHP_SELF]\">";
   return;

}
/* Sets the value of the logged_in variable, which can be used in your code */
$logged_in = checkLogin();

?>

Dani AI

Generated

Good catch by — the original bug was purely a control‑flow issue: in PHP an elseif must directly follow the if/previous elseif block. If you insert other statements between them you break that chain. The PHP manual covers the syntax and behaviour in detail: if/elseif/else control structures.

Two practical ways to avoid the problem and make the code clearer:

  • Validate input first (presence, length). If a validation check fails, return/display the error immediately. This prevents unnecessary database calls and keeps the logic linear.
  • After validation, perform the database lookup and do authentication in its own block (or use early returns). That keeps if/elseif chains simple and prevents mixing unrelated statements between branches.

Security and robustness recommendations not shown in the thread:

  • Use strong password handling: password_hash() and password_verify() instead of older hashes. See PHP docs: password_hash.
  • Use prepared statements (PDO or mysqli) to prevent SQL injection: PDO prepared statements.
  • Do not store passwords (even hashed) in cookies or session variables. Use secure, random long‑lived tokens for "remember me" and store them server side.
  • Regenerate the session ID after successful login (session_regenerate_id) and set cookies with HttpOnly, Secure, and same‑site flags.

Small example of the recommended password workflow:

$hash = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($inputPassword, $hash)) {
    // authenticated
}

Also avoid die() for user errors, use header('Location: ...') + exit for redirects (and ensure no prior output), sanitize displayed messages with htmlspecialchars, and log failed attempts for monitoring. Overall, , your final structure is fine functionally — consider the security hardening above before deploying.

Recommended Answers

All 2 Replies

Check if this works (I just rearranged some lines):

<?php
/**
 * Checks to see if the user has submitted his
 * username and password through the login form,
 * if so, checks authenticity in database and
 * creates session.
 */

if(isset($_POST['sublogin'])){
   
   $_POST['user'] = trim($_POST['user']);
   
   /* Checks that username is in database and password is correct */
   $md5pass = md5($_POST['pass']);
   $result = confirmUser($_POST['user'], $md5pass);
	
   /* Check that all fields were typed in */
   if(!$_POST['user'] || !$_POST['pass']){
      echo "<p>Missed a field</p>";
   }
   
   elseif(strlen($_POST['user']) > 30){
      echo "<p>Sorry too long</p>";
   }  
   
   /* Check error codes */
   elseif($result == 1){
      die('That username doesn\'t exist in our database.');
   }
   elseif($result == 2){
      die('Incorrect password, please try again.');
   }

	else{
   /* Username and password correct, register session variables */
   $_POST['user'] = stripslashes($_POST['user']);
   $_SESSION['username'] = $_POST['user'];
   $_SESSION['password'] = $md5pass;

   /**
    * This is the cool part: the user has requested that we remember that
    * he's logged in, so we set two cookies. One to hold his username,
    * and one to hold his md5 encrypted password. We set them both to
    * expire in 100 days. Now, next time he comes to our site, we will
    * log him in automatically.
    */
   if(isset($_POST['remember'])){
      setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/");
      setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
   }
	}

   /* Quick self-redirect to avoid resending data on refresh */
   echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[PHP_SELF]\">";
   return;

}
/* Sets the value of the logged_in variable, which can be used in your code */
$logged_in = checkLogin();

?>

Thanks but ive sorted it now, got it going like this

if(isset($_POST['sublogin'])){
   
   $_POST['user'] = trim($_POST['user']);
	
   /* Check that all fields were typed in */
   if(!$_POST['user'] || !$_POST['pass']){
      echo "<p class='log_in'>Oops!</p>";
   }
   
   
   /* Checks that username is in database and password is correct */
   $md5pass = md5($_POST['pass']);
   $result = confirmUser($_POST['user'], $md5pass);

   /* Check error codes */
   if($result == 1){
      echo "<p class='log_in'>Username not existant!</p>";
   }
   else if($result == 2){
      echo "<p class='log_in'>Password not existant!</p>";
   }

   else{
   /* Username and password correct, register session variables */
   $_POST['user'] = stripslashes($_POST['user']);
   $_SESSION['username'] = $_POST['user'];
   $_SESSION['password'] = $md5pass;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.