- Instead of storing the plain text password, store the password's hash
(example is using bcrypt)
+----------+--------------------------------------------------------------+
| username | password |
+----------+--------------------------------------------------------------+
| bsmith | $2y$10$HjaogAYhazNAPqeLb57tNeGpQmvYLu1Pg8y8GdyULi6fKLMN/1Pum |
| jwhite | $2y$10$hONd1dWW2.Bk/9P8SCTHg.fVFH.gJHVYM6dipYIUUuAZNGLiZwXea |
| sblack | $2y$10$i8fsnV3xLNXJawIjJLPZP.J9b4F6pumVCcfaoqfZoHx2875xhZlf. |
+----------+--------------------------------------------------------------+
- Use PHP password_hash(password, hashFunction) function to produce a bcrypt hash
of the password for inserting into the database
// Get user data
$username = $mysqli->real_escape_string($_POST['username']);
$password = $_POST['password'];
$name = $mysqli->real_escape_string($_POST['name']);
// Create bcrypt hash of the password
$password_hash = password_hash($password, PASSWORD_BCRYPT);
// Insert new user into the database
$cmd = "INSERT INTO Users VALUES ('$username', '$password_hash', '$name', '', NULL)";
- When user provides their username and password, use password_verify(password, hash)
to see if the bcrypt hash of their password matches the hash in the database
// Get the submitted username and password
$username = $mysqli->real_escape_string($_POST['username']);
$password = $_POST['password'];
// Get the password hash for this username
$sql = "SELECT username, password FROM Users WHERE username='$username'";
$result = $mysqli->query($sql) or
die("Error executing query: ($mysqli->errno) $mysqli->error<br>SQL = $sql");
if ($result->num_rows == 0)
echo "Sorry, but that username could not be found.";
else
{
$row = $result->fetch_assoc();
// See if bcrypt hash of submitted password matches the database
if (password_verify($password, $row['password']))
echo "Welcome, row[$username]!";
else
echo "Sorry, the password is not correct.";
}