生成动态PHP

时间:2016-04-05 17:06:42

标签: php

我在生成Bcrypt密码时遇到问题。而不是在哈希变量和if语句中手动输入它们我想在表单HTML中生成它们。我不知道该怎么做。

    <?php
/*in the if statment make sure that the password is the same as in hash variable*/
$options = array('cost' => 12);
echo "Bcrypt: ";
echo $hash = password_hash("yourpassword", PASSWORD_BCRYPT, $options);
echo "<br>";
echo "Verify now:<br>";
if (password_verify('yourpassword', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}


?>
<p>Please enter a value to encrypt!</p>
<form action="invite.php">
  Key:<br>
  <input type="text" name="firstname"><br>
  <input type="submit" value="Submit">



</form>

1 个答案:

答案 0 :(得分:4)

我会尝试回答这个问题,如果这就是问题所在。

您可以将一个变量分配给POST数组(并使用表单的post方法)作为两个函数的第一个参数传递,并检查它是否为空并使用NSLocationWhenInUseUsageDescription针对命名的输入/提交。

N.B。:以下代码编写为在同一文件中使用,就像我使用isset()一样。如果您打算在两个单独的文件中使用它,那么无论如何都要将操作更改为用于它的文件名。

action=""

旁注:如果这是用于密码,那么您应该将输入类型更改为&#34;密码&#34;而不是&#34;文字&#34;。

如果您以后想将此作为登录系统使用,请查看ircmaxell的答案https://stackoverflow.com/a/29778421/

如果使用PDO并准备好声明。

从他的回答中拉出来:

只需使用图书馆。认真。它们存在是有原因的。

不要自己动手。如果你正在创造自己的盐,你做错了。你应该使用一个为你处理这个问题的库。

<?php 

/*in the if statment make sure that the password is the same as in hash variable*/
$options = array('cost' => 12);
echo "Bcrypt: ";

if(isset($_POST['submit'])){

    if(!empty($_POST['firstname'])){

        $their_input = $_POST['firstname'];

            echo $hash = password_hash($their_input, PASSWORD_BCRYPT, $options);

            echo "<br>";
            echo "Verify now:<br>";


            if (password_verify($their_input, $hash)) {
                echo 'Password is valid!';
            } else {
                echo 'Invalid password.';
            }

    }
    else{
       echo "You left this empty.";
    }

}

?>

<p>Please enter a value to hash!</p>
<form action="" method="post">
  Key:<br>
  <input type="text" name="firstname"><br>
  <input type="submit" name="submit" value="Submit">

</form>

登录时:

$dbh = new PDO(...);

$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);

$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);

关于列长的重要说明:

如果您决定使用$sql = "SELECT * FROM users WHERE username = ?"; $stmt = $dbh->prepare($sql); $result = $stmt->execute([$_POST['username']]); $users = $result->fetchAll(); if (isset($users[0]) { if (password_verify($_POST['password'], $users[0]->password) { // valid login } else { // invalid password } } else { // invalid username } 或兼容包(如果PHP <5.5)https://github.com/ircmaxell/password_compat/,请务必注意,如果您当前的密码列的长度为任何低于60的东西,都需要改为(或更高)。手册建议长度为255。

您需要更改列的长度并重新开始使用新哈希才能使其生效。否则,MySQL将无声地失败。