简体   繁体   中英

Add password_hash() to php with txt flatfile database

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

  1. Do echo password_hash('passone') for each of your passwords, store the resulting long gobbledygook string in your text file.
  2. Instead of if ($_POST['pass'] == $item[0]) ,
    you do 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>';
}
  • word of warning though. personally, i do not like password_hash, because its not easy to integrate with applications written in other languages (to c++ in my scenario), the hash structure is not clearly defined (as far as i know), short of reading the php interpreter's source code..

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM