I am trying to understand how password_hash()
function works.
I have got this ultra-simplified php login (completely unsafe, just designed to learn) with four passwords chosen by me.
<?php
$data = file_get_contents('pass.txt');
if($_POST['pass']) {
$line = explode("\n", $data);
for($i = 0; $i<count($line); $i++) {
$item = explode("#", $line[$i]);
if($_POST['pass'] == $item[0]) {
echo "Welcome! You're logged in!";
}
}
}
else { echo '<form method="POST" action="">
<input type="password" name="pass">
<input type="submit">
<form>';
}
?>
and this pass.txt
, where the passwords are kept (.txt flatfile database):
passone
passtwo
passthree
passfour
Is it possible to add password_hash() function to my code?
I guess the php should be able to rewrite the database for this purpose, as this functions rewrites the passwords every time you login.
Thanks guys XXX
echo password_hash('passone')
for each of your passwords, store the resulting long gobbledygook string in your text file. if ($_POST['pass'] == $item[0])
, if (password_verify($_POST['pass'], $item[0]))
. That is, you use password_verify
on the plaintext password and a hashed password from your text file. password_hash
creates a random salt during the hash process. This random salt is part of the gobbledygook string it returns! You need to reuse that random salt during the comparison. password_verify
takes care of that for you.
That's all that's needed.
yes.
oh, and you should use isset, else you might get PHP errors. and you should break; after finding a correct password, the rest is just a waste of cpu.
first for creating your pass.txt:
<?php
$passes=array(
'passone','passtwo','passthree'
);
foreach($passes as &$pass){
$pass=password_hash($pass,PASSWORD_DEFAULT);
}
file_put_contents("pass.txt",implode("\n",$passes));
then do like
<?php
$data = file_get_contents('pass.txt');
if(array_key_exists('pass',$_POST)){
$lines = explode("\n", $data);
for($i = 0; $i<count($lines); $i++) {
if(password_verify($_POST['pass'],$lines[$i])) {
echo "Welcome! You're logged in!";
break;
}
}
}
else { echo '<form method="POST" action="">
<input type="password" name="pass">
<input type="submit">
<form>';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.