php - Efficiently checking a hashed password from database -
firstly have tried best find definitive answer on this. secondly, code appears work, want confirm doing in efficient manner , not leaving myself open security breaches.
firstly, use php password_hash when adding user admin table;
$stmt = $dbh->prepare("insert admin (username, password) values (:username, :password)"); $stmt->bindparam(':username', $username); $stmt->bindparam(':password', $password); $password = password_hash('password', password_default);
secondly, when user attempts login, retrieve users admin table matching username only, couldn't see way check hash during query (this part unsure if there better way), , define $password variable post input;
$stmt = $dbh->prepare("select * admin username = :username"); $stmt->bindparam(':username', $username); $username = $_post['username']; // define $password use in password verify $password = $_post['password'];
thirdly, if there result query, run password_verify on user input check match, , branch depending on true or false.
if ($row = $stmt->fetch(pdo::fetch_assoc)) { if (password_verify($password, $row['password'])) { session_start(); foreach ($row $user) { $_session['user'] = $row['id']; } } else { $errors = true; } header('location: leads.php'); } else { $errors = true; }
i know there many different ways hash / secure passwords, using native password_hash functions way decided go, question have done right / there better way?
thanks in advance.
basically, code looks quite okay, except things mentioned. ask improvements, performance related ones, here go:
- add index on
username
if table gets lot of entries, remove index
username
, add new column calledhash
index , rewrite insert , select this:insert admin (username, password, hash) values (:username, :password, crc32(username))
select * admin username = :username , hash=crc32(:username)
i assume, use mysql, adding limit 1
query helps optimizer , stops searching after row found.
avoiding foreach
-loop possible, if work 1 row.
btw: header('location: leads.php');
should read header('location: leads.php');
, using absolute paths makes things more robust.
Comments
Post a Comment