我使用password_hash
將密碼存儲在類型爲VARCHAR(255)的MySQL數據庫字段中。當我嘗試登錄用戶並驗證憑據時,password_verify
函數始終返回false。PHP password_hash和password_verify不使用MySQL
下面是摘錄的代碼存儲在MySQL數據庫中的密碼:即檢查密碼
$password_hash = password_hash($password, PASSWORD_DEFAULT);
// Generate API Key
$api_key = $this->generateApiKey();
// Insert Query
$stmt = $this->conn->prepare("INSERT INTO user(email, password, name, api_key, status) values(?, ?, ?, ?, 1)");
$stmt->bind_param("ssss", $email, $password_hash, $name, $api_key);
$result = $stmt->execute();
$stmt->close();
而且一段代碼:
// Query user by email
$stmt = $this->conn->prepare("SELECT password FROM user WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($password_hash);
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Found user with that email address
// Now verify the password
$stmt->fetch();
$stmt->close();
if (password_verify($password, $password_hash)) {
// User password is correct
return TRUE;
然後我寫了這個測試代碼並搶下直接來自MySQL字段的數據仍然失敗。當我在同一個文件中創建password_hash(下面文件中的$ hash2)時 - 那麼密碼驗證正確。
$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';
$hash2 = password_hash($password, PASSWORD_DEFAULT);
echo $hash . " - " . strlen($hash);
echo "<br />";
echo $hash2 . " - " . strlen($hash2);
echo "<br />";
if (password_verify($password, $hash)) {
echo "Password Valid!";
} else {
echo "Password invalid!";
}
echo "<br /><br />";
if (password_verify($password, $hash2)) {
echo "Password 2 Valid!";
} else {
echo "Password 2 invalid!";
}
你確定這是正確的哈希? – 2015-02-23 03:51:26
雖然我注意到每次刷新我的測試頁時$ hash2變量都會改變,但我並不是100%確定crypt如何工作以充分理解原因。 – mattdonders 2015-02-23 03:53:39