Hash Password in PDO Error/Notice

2019-06-09 01:21发布

If I run this I get the following error:

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

I dont know how to fix that. It's still successful and the data is hashed in the database, but I don't want this notice.

$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;

Thanks in advance.

1条回答
乱世女痞
2楼-- · 2019-06-09 01:46

You cannot do password_hash($_POST['password'], PASSWORD_BCRYPT) inside bindParam, because password_hash returns a string, do:

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

If you wish to leave the values there use bindValue:

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

because it allows varibles by reference.

Explanation:

bindParam expects a variable or const it can't be a primitive type such as a string or an int, ..., explicitly (ex: "some_hardcoded_string") neither can it be a function that returns one of this types.

bindValue can receive references and primitive types as an argument.


Examples for both:

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

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

SHA1 is returns a value, it could be a number 12345 (let's say for the sake of the example)

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

or a string.

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

retated questions:

查看更多
登录 后发表回答