PHP密码_hash怎么检查?

时间:2016-10-19 10:19:59

标签: php

我尝试了一个名为" password_hash"的PHP新功能。我想只有一个密码来检查它是否等于静态密码。如果密码相等,那么我想转到另一页。

这是我尝试的代码:

    $gen_pass  =    password_hash("test", PASSWORD_DEFAULT);
    if(isset($_POST["submit_verify"]))
    {
         $pass_verify = filter_var($_POST["pass_verify"], 
         FILTER_SANITIZE_SPECIAL_CHARS);
         if($pass_verify)
         {
             if(password_verify($pass_verify, $gen_pass))
                echo "<h1>SUCCESS</h1>";

             else 
                header("location: ../index");
        }
    else $error_msg     =   "Error!";
}

但是当我尝试它时,该网站是令人耳目一新的,没有任何反应。 当我在输入中写入错误的密码时,我在index.php页面上成功。

1 个答案:

答案 0 :(得分:2)

$options  = [ 'cost' => 12 ];
$gen_pass = password_hash( "test", PASSWORD_BCRYPT, $options );
    if(isset($_POST["submit_verify"]))
    {
         if( password_verify( $_POST[ "submit_verify" ], $gen_pass ) )
         {
                if( password_needs_rehash( 'password_from_database', PASSWORD_BCRYPT, $this->cost ) )
                {
                  $new_hashed_password = password_hash( "new_password", PASSWORD_BCRYPT, $options );
                  // Run and update script to update the password in the database
                }
                echo "<h1>SUCCESS</h1>";
         }
         else 
         {             
                header("location: ../index");
         }
    }

使用$pass_verify = filter_var($_POST["pass_verify"], FILTER_SANITIZE_SPECIAL_CHARS);我可以告诉我将删除并替换<>&如果密码包含这些字符会发生什么?

要确定最佳成本,您可以使用这样的函数,返回的数字是用于所花费时间的成本值。将$min_ms更改为您想要的任何时间,它将为您提供成本。这取自PHP password_hash页面。

function getOptimalBcryptCostParameter($min_ms = 1000) {
    for ($i = 4; $i < 31; $i++) {
        $options = [ 'cost' => $i ];
        $time_start = microtime(true);
        password_hash("PASSWORD_HERE", PASSWORD_BCRYPT, $options);
        $time_end = microtime(true);
        echo "Time to hash: ".($time_end - $time_start).' with a  cost of '.$i.'<br>';
        if (($time_end - $time_start) * 1000 > $min_ms) {
            return $i;
        }
    }
}
echo getOptimalBcryptCostParameter(); // prints 12 in my case