PHP不会将散列密码写入文件吗?

时间:2016-04-14 12:53:20

标签: php

我目前正在尝试测试PHP的密码验证,并使用以下代码进行测试:

HTML文件:

<form action="post.php" method="post" id="set">
    <label>Set</label>
    <input name="password1" id="password1">
    <input type="submit" name="submit1" value="Add password">
</form>
<form action="check.php" id="check">
    <label>Check</label>
    <input name="password2" id="password2">
    <input type="submit" name="submit2" value="Test Password">
</form>     

PHP将密码添加到文件:

<?php
    $password = $_POST['password1'];
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $file = 'hash.txt';
    file_put_contents($file, $hashed_password, FILE_APPEND);
?>

PHP将输入的密码与文件中的密码进行比较:

<?php
    $password = $_POST['password2'];
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    if (password_verify($password, $hashed_password)) {
        echo 'Correct';
    }
    echo 'Wrong';
?> 

我知道将密码存储到文件中并不是最聪明的想法,但这只是为了测试。

所以我要做的是以第一种形式输入密码,点击提交并将散列密码存储到hash.txt然后当我在第二个字段中重新输入密码时,它应该有希望回显'正确'。

我遇到的问题是,当我按提交时,在第一个表单上,它会将我发送到post.php,并且不会将散列密码添加到hash.txt

1 个答案:

答案 0 :(得分:1)

Check.php需要从您保存的文件中读取密码才能对其进行检查。

另外,if then else会更好地输出您的信息,否则您将始终收到echo 'Wrong';消息

如果您在此脚本中启用了错误报告,则可能非常明显。我假设您正在使用LIVE服务器,因此默认情况下它们将被关闭。

post.php添加一些错误报告并删除FILE_APPEND,因为此代码无法处理存储在该文件中的多个哈希。也许这就是你的一个问题!

<?php
    error_reporting(E_ALL); 
    ini_set('display_errors', 1);

    $password = $_POST['password1'];
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $file = 'hash.txt';
    file_put_contents($file, $hashed_password);
?>

Check.php

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1);

$password = $_POST['password2'];

$hashed_password= file_get_contents('hash.txt');

if(password_verify($password, $hashed_password)) {
    echo 'Correct';    
} else {
    echo 'Wrong';
}
?>