Should I validate a username and pass word by searching for both in the SQL table Or Should I find the username then match the pass word with a PHP if statement?
The thing is… You are supposed to store salted, hashed passwords in the database. Since these are individually salted per user/password, you cannot look them up directly with password = ?
, because you don't know the salt and therefore cannot calculate the matching hash in advance. If you're doing this properly, you must fetch the user record by username first, then validate the password hash using the retrieved salt/hash. Pseudocode:
$user = fetch_from_database($_POST['username']);
if (!$user) {
throw new Exception("User doesn't exist");
}
if (!password_verify($_POST['password'], $user['password_hash'])) {
throw new Exception('Invalid password');
}
echo 'Welcome ', $user['name'];
See http://php.net/password_hash, http://php.net/password_verify.
From the 2 listed above, the second one is more secure, because first one is more tilted towards SQL injection.
SELECT * FROM table WHERE username = $username AND password =$password
In this code if the value of username and password entered is something like "a or ('a'='a')" the code will be modified to
SELECT * FROM table WHERE username = a or ('a' = 'a') AND password = a or ('a' = 'a')
Which means a clear code for listing all your data.
Whereas in the second case , IF condition will consider the value as a single string only. So second is the best among the 2 u mentioned..
Hope this helps