我创建了一个函数(isPasswordCorrect)来检查数据库中的哈希密码的用户密码。由于某种原因,在函数的MySQL查询部分之后,$ password的值将丢失。
用户电子邮件和密码从表单传递到函数。调用函数后会存在这些值,如下面的代码所示。
我无法理解Try Catch后$ password值变为空字符串的方式或原因。我可以通过将$ password值保存到SESSION变量中来实现它,但这看起来不正确且不合需要。
代码与$ _SESSION ['password']一起使用,但这并不能解释$ password值发生了什么。
感谢任何帮助。
<?php
// Boolean function to check user password against stored password
function isPasswordCorrect($email, $password){
// Check if values being passed into function - OK
echo 'email: ' . $email . '<br>';
echo 'password: ' . $password;
// Solution to make this work, but not desirable
$_SESSION['password'] = $password;
// Connect to database
include 'admin/includes/dbconnect-local.php';
// Access table to retrieve hashed password
try
{
$sql = 'SELECT password FROM user
WHERE email = :email';
$s = $db->prepare($sql);
$s->bindValue(':email', $email);
$s->execute();
}
catch(PDOException $e)
{
$error = 'Error fetching password.' . $e->getMessage();
include 'admin/content_editors/error.html.php';
exit();
}
// Assign single row result to $result
$result = $s->fetch(PDO::FETCH_ASSOC);
// Verify hashed password value was retrieved and being passed through function - OK
echo "<pre>";
print_r($result);
echo "</pre>";
/***********************************************************************************/
// Verify $password value. DISCOVER THAT $password value is now EMPTY STRING! - NOT OK
echo 'password: ' . $password . '<br>';
// Verify SESSION password value - OK
echo 'SESSION password: ' . $_SESSION['password'];
// Check for match using password_verify() - WORKS ONLY USING $_SESSION['password'] - NOT REALLY OK
if(password_verify($_SESSION['password'], $result['password']))
{
return TRUE;
}
else
{
return FALSE;
}
}
// Call function after post of submitted data
if(isset($_POST['action']) && $_POST['action'] === 'submit')
{
if(isPasswordCorrect($_POST['email'], $_POST['password']))
{
echo '<p style="color:#0000ff;">Match found!</p>';
// Check values used in function - OK
echo '<p>' . $_POST['email'] . '</p>';
echo '<p>' . $_POST['password'] . '</p>';
}
else
{
echo '<p style="color:#ff0000;">Sorry, match not found.</p>';
// Check values used in function - OK
echo '<p>' . $_POST['email'] . '</p>';
echo '<p>' . $_POST['password'] . '</p>';
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Password Verify</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="email" placeholder=" Email">
<input type="text" name="password" placeholder=" Password">
<button type="submit" name="action" value="submit">Submit</button>
</form>
</body>
</html>
答案 0 :(得分:0)
include
语句基本上告诉PHP将包含文件的内容复制并粘贴到该位置的脚本中,然后继续执行。
如果$password
文件中有'admin/includes/dbconnect-local.php'
个变量,它会覆盖您函数中的$password
变量。