PHP can I combine these if statements.

Associate
Joined
11 Oct 2008
Posts
268
Hey guys, I have cobbled together a little bit of code to display an error message if a submitted username or passwords is wrong. At the moment I have to do the logic for the user names and password seperatly or it will not work.

Is there anyway to combine the 2 if/elseif statements?

PHP:
if ((isset($_POST['username'])) && ($username !== $db_username)) {     

    $loginmsg ="Username/password is wrong";

    } 
    elseif ((isset($_POST['password'])) && ($password !== $db_password)) {     

    $loginmsg ="Username/password is wrong";
    }
 
You're using register_globals by the looks of it. Please don't. If submit the post variables db_username and db_password it would override whatever value is in those variables that you are expecting.

You also have some odd logic. If the variables are not set, then the request proceeds as if they are logged in.

To answer the question and the above problems:

PHP:
if (!isset($_POST['username']) || ($_POST['username'] !== $db_username) || !isset($_POST['password']) || ($_POST['password'] !== $db_password)) {
  $loginmsg ="Username/password is wrong";
}
 
Last edited:
I personally wouldn't do it that way around mate, i'd do a search on the DB for the correct username and password, if they are returned allow the login, if not don't.

Obviously clean the inputs etc.
 
It also looks like you are storing passwords in your database in plain text. That is bad. Use a decent cryptographic hash function to store passwords such as bcrypt or SHA-512.
 
Back
Top Bottom