用户名正确,密码不正确?

时间:2010-12-25 15:57:13

标签: php sql login

在登录系统中,如何判断用户输入的密码是否错误?你执行两个SQL查询,一个用于查找用户名,然后一个用于查找用户名和匹配(salted + hashed等)密码?我问这个是因为如果用户输错密码,我想更新我的failed_login_attempts列。

如果你执行两个查询不会增加开销吗?

如果您执行了这样的查询,您如何判断输入的密码是否正确,或者用户名是否不存在:

 SELECT * FROM author 
 WHERE username = '$username'
 AND password = '$password'
 LIMIT 1

(^ NB:我保持简单,将使用哈希和盐,并将清理真实输入中的输入。)

这样的事情:

$user = perform_Query() // get username and password?

 if ($user['username'] == $username && $user['password'] == $password)
 {
     return $user;
 }
 elseif($user['username'] == $username && $user['password'] !== $password)
 {   // here the password doesn't match
     // update failed_login_attemps += 1
 }

5 个答案:

答案 0 :(得分:4)

你是在思考它。只需要一个查询:

SELECT * FROM author WHERE username = '$username';

然后做:

if ($user['password'] == saltedHash($password,$user['salt'])) {
    return "successful";
}
else {
    return "failed";
}

用户名必须是唯一的。否则这将无效。我建议不要将用户名设置为非唯一的,因为它会导致许多其他问题。

答案 1 :(得分:3)

  

如果你执行两次查询会不会增加开销?

我说真的没关系。许多复杂的Web框架每个请求发出数十个或数百个查询。或多或少不会改变很多东西。

我认为这取决于偏好。获取整个用户行,然后检查PHP端的密码是我认为最有意义的,因为您已经拥有更新failed_logins列所需的ID。

答案 2 :(得分:0)

我们所做的是执行一个查询来查找用户(基于用户ID),然后选择UserId,PwSalt和PwHash。

如果找不到用户,则我们知道它是无效的用户名。

如果找到用户,我们将密码哈希并将其与查询中的pwHash进行比较。如果哈希值不匹配,我们会更新失败的登录尝试。

答案 3 :(得分:0)

在您的代码中,如果用户名或密码不正确,$ user将为空

SELECT password = '$password' AS is_legit, * 
FROM author 
WHERE username = '$username'
LIMIT 1

$user = perform_Query() // get username and password?
// $user will be empty if the username is incorrect
$user_exists = $user.length > 0;
// to make sure we don't address a 
// non-existent array element
if($user_exists && $user['password'] == $password){ 
     return $user;
}
elseif($user_exists && $user['password'] !== $password)
{   // here the password doesn't match, but the user does
    // update failed_login_attemps += 1
    // be sure to let the user know that the penetration
    // attempt is halfway complete
}
else{
    // F4il
}

答案 4 :(得分:-1)

和许多其他人)创建登录系统的方式如下:

  • 注册时
    • 创建一个唯一的哈希并存储以及用户名,密码
  • 登录时
    • 从数据库中提取用户名,密码,哈希
    • 使用条款WHERE username = '$username'
    • 如果是1行,则用户名是正确的
    • 使用hash($post_pass,$user_hash)构建已编译的哈希,并与$ user_pass
    • 进行比较

此外,如果你在方法的1点返回任何东西,那么无法运行,所以

if ($user['username'] == $username && $user['password'] == $password)
 {
     return $user;
 }
 elseif($user['username'] == $username && $user['password'] !== $password)
 {   // here the password doesn't match
     // update failed_login_attemps += 1
 }

可以修改为

if ($user['username'] == $username && $user['password'] == $password)
{
    return $user;
}
return false

因为如果满足($user['username'] == $username && $user['password'] == $password),那么将在那里执行返回,因为不会执行false。

希望这有帮助。

相关问题