Yes. Query your database for someone with the given username and password using a query that would look something like this:
select * from users where Name = 'john.doe' and Password = 'hunter2' limit 1
If it yields any rows, the user exists, and you should let them in. If there are no rows, then that combination of username and password is invalid and you should not let them in.
That's the basics, but if you're actually going to put this into production, you'll want to make a few more changes:
Escape the data you're putting in the query appropriately or use prepared queries. As is, your code is vulnerable to an SQL injection attack. Say, for example, I tried to create an account with an apostrophe in the username or password. Your code would break. This could be leveraged for malicious means, too, so you really should patch that up.
The simplest way to patch it up would be to escape everything before you put it into the query, using, say, mysql_real_escape_string
. That'll probably work, but even better (since the whole mysql_
family of functions is deprecated) would be to use prepared queries and PDO, as I've shown below.
Hash and salt your passwords so a database compromise (which could happen rather easily if the above vulnerability is left unpatched) will not reveal all the passwords.
Your code might then look like this:
// You'd probably want to put these in a separate configuration file.
$db = new PDO('mysql:dbname=test', 'my_mysql_user', 'hunter2');
// Make any errors throw an exception.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db->prepare('select * from users where Name = :name limit 1');
$query->bindValue(":name", $_POST['username'], PDO::PARAM_STR);
$row = $query->fetch(PDO::FETCH_ASSOC);
if($row === FALSE) {
// User not in the database; don't let them in.
}
$calculatedHash = hash("sha512", $row['PasswordSalt'] . $_POST['password']);
if($calculatedHash === $row['PasswordHash']) {
// Password's right. Let them in.
}else{
// Password's wrong. Keep them out.
}
Further improvements would be to use, say, bcrypt rather than salted SHA-512.