dpmwy80068
2014-01-25 18:17
浏览 34
已采纳

php:mysqli登录脚本因未知原因而失败

So I have my log in script that I am trying to get to work, but when I try to log in it always says no even if the test I included below says expected:(password hash here) found: (same password hash here) I have changed the code so many times in attempts to fix it, and done a load of Google searches(for those who want to give me lmgtfy links) trying to fix it. I've included as much of the code as I can without having to add fake details so stack overflow would let me add more code:

Actual script:

else{
    $login = login($username, $password);
    if ($login === false) {
        $errors[] = 'That username/password is incorrect';
    } else {
        echo "ok";
        $_SESSION['user_id'] = $login;
        header('Location: index2.php');
        exit();
    }
}
print_r($errors);
//echo "expected to see: ". $pass. " "; //this was a test
//echo "found: ".$passen;               //this was too

Login function:

function login($username, $password){
$user_id = sanitize($username);

$db = get_my_db();
$username = sanitize($username);
$password = md5($password);

$sql = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND          `password` = '$password'";

return ($db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` =   '$username' AND `password` = '$password'") === 1) ? $user_id : false; }

And the sanitize() function is just mysqli_real_escape_string($data) if you want anything else, let me know, and i'll put it in. By the way, the tests script was this: and the expected function just turned the $password into an md5.

$res = $db->query("SELECT `password` FROM users WHERE username = '$username'");
$row = $res->fetch_assoc(); 
$pass = $row['password'];
$passen = expected($password); 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyan2680 2014-01-25 18:25
    已采纳

    I do not know where it fails, but a few tips:

    • use salted sha1 passwords
    • do not create functions like sanitize(),get_my_db(), those dont even speedup your work
    • mysqli_ should be called with $con first parameter, like mysqli_real_escape_string($con, $var);
    • to get working global $con in local function, write function login() { global $con; }
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题