PDO 中的哈希密码 Error/Notice

Hash Password in PDO Error/Notice

如果我运行这个我得到以下错误:

Notice: Only variables should be passed by reference in /var/www/interface/register.php on line 11 Success

我不知道如何解决这个问题。它仍然成功并且数据在数据库中被散列,但我不想要这个通知。

$sql = " INSERT INTO users (username, password) VALUES (:username, :password)";
    $stmt = $conn->prepare($sql);

    $stmt->bindParam(':username', $_POST['username']);
    $stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));


    if ($stmt->execute()) :
        die('Success');
    else:
        die('Fail');
    endif;

提前致谢。

你不能在 bindParam, because password_hash returns 字符串中执行 password_hash($_POST['password'], PASSWORD_BCRYPT) ,执行:

$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password);

如果您希望保留这些值,请使用 bindValue:

$stmt->bindValue(':username', $_POST['username']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));

因为它允许引用变量。

解释:

bindParam 需要一个变量或 const 它不能是原始类型,例如字符串或 int,...,显式(例如:"some_hardcoded_string" ) 也不能是 returns 这种类型之一的函数。

bindValue 可以接收引用和原始类型作为参数。


两者的示例:

$query->bindParam(':user', $user, PDO::PARAM_STR);

$query->bindValue(':pass', sha1($password), PDO::PARAM_STR);

SHA1 是 returns 一个值,它可能是一个数字 12345(为了举例而假设)

$query->bindValue(':pass', 12345, PDO::PARAM_STR); 

或字符串。

$query->bindValue(':pass', 'hashed_password', PDO::PARAM_STR);

重复问题:

  • Strict Standards: Only variables should be passed by reference in m_auth
  • PDO pass by reference notice?
  • Strict Standards: Only variables should be passed by reference