I'm learning about PHP's hashing and salting functions and wanted to try it out, so I created a local database and table with two columns (username and password) in phpmyadmin and populated it with a single username and hashed password.
Now I'm wondering, is there a better way to do what I've done, or something I shouldn't be doing?
(I know having specific error messages is bad, this is just for testing purposes.)
Database: db_users
Table: users
username: username
password: $2y$11$uJiGb3suyiupJNn9MuHNpu7dt6BwB9kS6I4fHDutknggio5PeJ17u
$DB_NAME = "db_users";
$TABLE_NAME = "users";
// The submitted values from the username and password textboxes
$username = $_POST["username"];
$password = $_POST["password"];
// Hash and salt options
$options = [
'cost' => 11,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$connection = new PDO("mysql:host=localhost", "root", "password");
$sql = $connection->prepare("
SELECT username
FROM $DB_NAME.$TABLE_NAME
WHERE (username=:user);");
$sql->bindParam(":user", $username);
$sql->execute();
$rows = $sql->fetch(PDO::FETCH_NUM);
// Check if username exists in database
if ($rows > 0) {
// Check if passwords match
$sql = $connection->prepare("
SELECT password
FROM $DB_NAME.$TABLE_NAME
WHERE (username=:user);");
$sql->bindParam(":user", $username);
$sql->execute();
if (password_verify($password, $sql->fetch()[0]) > 0) {
echo "Username and password match";
} else {
echo "Username and password do not match";
}
} else {
echo "Username does not exist";
}