2013-06-19 63 views
0

我的登录表单无法识别现有用户。我存储在数据库中的密码使用PHP的crypt()函数加密。当用户注册他们的密码时也会被加密并插入到数据库中。PHP/MySQL/PDO - 无法识别现有用户的登录表格

正如你在下面的代码中看到的,它检查下面输入的密码是否匹配,但是每当我输入存储在数据库中的密码时,用相应的用户名称表示用户不存在。

我是新来的PDO,这是我第一次使用它,通常如果我只是使用MySQL它工作正常,但由于某种原因,这不是,我已经改变了一些代码,但它仍然没有工作。任何人都知道为什么/在哪里/我在做什么错了代码。

include "connect.php"; 

$username = $_POST['username']; 
$password = $_POST['password']; 

$sql = "SELECT * FROM users WHERE username=:username"; 
$statement = $db->prepare($sql); 
$statement->bindValue(':username',$username,PDO::PARAM_STR); 

if($statement->execute()) 
{ 
    if($statement->rowCount() == 1) 
    { 
     $row = $statement->fetch(PDO::FETCH_ASSOC); 

     if(crypt($password, $row['username']) == $row['user_password']) 
     { 
      $username = $row['username']; 
      $email = $row['email']; 

      $_SESSION['username'] = $username; 
      $_SESSION['email'] = $email; 
      $_SESSION['logged_in'] = 1; 

      header("Location: index.php"); 
      exit; 
     } 
     else 
     { 
      include "error_login.php"; 
     } 
    } 
    else 
    { 
     include "error_login.php"; 
    } 
} 
+0

你的if语句都包含'error_login',如果它们是假的 - 你知道哪一个被调用吗? – andrewsi

+0

使用'session_start();'顶部也 – pl71

+0

@andrew:但只有当地穴不匹配。 –

回答

0
if(crypt($password, $row['username']) == $row['user_password']) 

应该

if(crypt($password) == $row['user_password']) 
0

与它存储的散列值的验证密码,你需要知道的盐和使用之前生成散列值的算法。这个salt可以从存储的散列值中提取,因为crypt()将它存储为结果字符串的一部分。

if (crypt($password, $row['user_password']) === $row['user_password']) 

PHP 5.5将有它自己的功能password_hash()和password_verify()准备,以简化生成散列BCrypt。我强烈建议使用这个优秀的api,或者早期的PHP版本是compatibility pack。用法非常简单:

// Hash a new password for storing in the database. 
// The function automatically generates a cryptographically safe salt. 
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT); 

// Check if the hash of the entered login password, matches the stored hash. 
// The salt and the cost factor will be extracted from $existingHashFromDb. 
$isPasswordCorrect = password_verify($password, $existingHashFromDb);