简体   繁体   English

如何验证用户登录的密码

[英]How to validate password for user login

<?php

include"database.php";

class User{
    public $db;


    public function __construct()
    {
        $this->db=new Database();
    }


    public function UserRegi($data){
        $name=$data['name'];
        $username=$data['username'];
        $email=$data['email'];
        $email_chk=$this->chkEmail($email);
        $password=md5($data['password']);


        if($name=="" || $username=="" || $email=="" || $password==""){
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>Any Field Must Not Be Empty !</div>';
            return $msg;
        }
        if(strlen($username)<3){
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>Username is too short !</div>';
            return $msg;
        }elseif(preg_match('/[^a-z0-9_-]+/i',$username)){
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>Username Must be contain alpha numerical dashes and underscore  !</div>';
            return $msg;
        }
        if(filter_var($email,FILTER_VALIDATE_EMAIL)===false){
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>Invalid Email Address !</div>';
            return $msg;
        }elseif($email_chk==true){
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>This Email Address Already Exists !</div>';
            return $msg; 
        }

        $sql="insert into tbl_user(name,username,email,password)values(:name,:username,:email,:password)";
        $query=$this->db->pdo->prepare($sql);
        $query->bindValue(":name",$name);
        $query->bindValue(":username",$username);
        $query->bindValue(":email",$email);
        $query->bindValue(":password",$password);
        $result=$query->execute();
        if($result){
            $msg='<div class="alert alert-success"><strong>Error ! </strong>Congrast User Registation successfull !</div>';
            return $msg; 
        }else{
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>User Ragistation Failed !</div>';
            return $msg; 
        }


    }

    public function chkEmail($email){
        $sql="SELECT * FROM tbl_user WHERE email=:email";
        $query=$this->db->pdo->prepare($sql);
        $query->bindValue(":email",$email);
        $query->execute();
        if($query->rowCount()>0){
            return true;
        }else{
            return false;
        }
    } 


    public function userLogin($data){
        $email=$data['email'];
        $email_chk=$this->chkEmail($email);
        $password=md5($data['password']);
        $pass_chk=$this->chkPassword($email,$password);

        if(filter_var($email,FILTER_VALIDATE_EMAIL)===false){
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>Invalid Email Address !</div>';
            return $msg;
        }elseif($email_chk==false){
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>This Email Address is not Exists !</div>';
            return $msg; 
        }
        if($pass_chk==true){
            $msg='<div class="alert alert-danger"><strong>Error ! </strong>Sorry Password incorrect !</div>';
            return $msg; 
        }

    }

    public function chkPassword($email,$password){
        $sql="SELECT * FROM tbl_user WHERE email=:email password=:password";
        $query=$this->db->pdo->prepare($sql);
        $query->bindValue(":email",$email);
        $query->bindValue(":password",$password);
        $query->execute();
        $result=$query->fetchAll(PDO::FETCH_ASSOC);
        if($result['password']==$password){
            return true;
        }else{
            return false;
        }
    } 

}


?>

It's showing this error:它显示此错误:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;致命错误:未捕获的 PDOException:SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'password='d41d8cd98f00b204e9800998ecf8427e'' at line 1 in C:\\xampp\\htdocs\\lr_new\\lib\\user.php:98 Stack trace: #0 C:\\xampp\\htdocs\\lr_new\\lib\\user.php(98): PDOStatement->execute() #1 C:\\xampp\\htdocs\\lr_new\\lib\\user.php(77): User->chkPassword('', 'd41d8cd98f00b20...') #2 C:\\xampp\\htdocs\\lr_new\\login.php(10): User->userLogin(Array) #3 {main} thrown in C:\\xampp\\htdocs\\lr_new\\lib\\user.php on line 98检查与您的 MariaDB 服务器版本相对应的手册,以获取在 C:\\xampp\\htdocs\\lr_new\\lib\\user.php:98 中的第 1 行的“password='d41d8cd98f00b204e9800998ecf8427e'”附近使用的正确语法:堆栈跟踪:#0 C :\\xampp\\htdocs\\lr_new\\lib\\user.php(98): PDOStatement->execute() #1 C:\\xampp\\htdocs\\lr_new\\lib\\user.php(77): User->chkPassword('' , 'd41d8cd98f00b20...') #2 C:\\xampp\\htdocs\\lr_new\\login.php(10): User->userLogin(Array) #3 {main} 被抛出到 C:\\xampp\\htdocs\\lr_new\\lib \\user.php 第 98 行

Your class is too complex and out of date, it needs to be rewriting almost half of it.你的类太复杂而且过时了,几乎需要重写一半。 I will show you example which I use in my demo, I used my own settings and my own table structer.我将向您展示我在演示中使用的示例,我使用了我自己的设置和我自己的表结构器。 Here is how you should call class :以下是您应该如何调用 class :

require_once 'config.php';
require_once '../class/user.php';

$email = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_DEFAULT);

if( $user->login( $email, $password) ) {
    die;
} else {
    $user->Msg();
    die;
}

And here your html codes of course in body tags, you probably using ajax so ne need action in form:在这里你的 html 代码当然在 body 标签中,你可能使用了 ajax,所以需要采取行动:

 <form method="POST"> <input type="text" id="username" name="username" value="dsdsd"> <input type="password" id="password" name="password" value="sdsd"> <input type="submit" name="LoginBtn" value="signup"> </form>

Your login function is to complex too, well your validating part is:您的登录功能也很复杂,您的验证部分是:

it should look like this :它应该是这样的:

public function login($email,$password){
    if(is_null($this->pdo)){
        $this->msg = 'Connection did not work out!';
        return false;
    }else{
        $pdo = $this->pdo;
        $stmt = $pdo->prepare('SELECT id, fname, lname, email, wrong_logins, password, user_role FROM users WHERE email = ? and confirmed = 1 limit 1');
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if(password_verify($password,$user['password'])){
                $this->user = $user;
                session_regenerate_id();
                $_SESSION['user']['id'] = $user['id'];
                $_SESSION['user']['fname'] = $user['fname'];
                $_SESSION['user']['lname'] = $user['lname'];
                $_SESSION['user']['email'] = $user['email'];
                $_SESSION['user']['user_role'] = $user['user_role'];
                return true;
        }else{
            $this->msg = 'Invalid login information or the account is not activated.';
            return false;
        } 
    }
}

Your register class should be up to date :您的注册类应该是最新的:

public function registration($email,$fname,$lname,$pass){
    $pdo = $this->pdo;
    if($this->checkEmail($email)){
        $this->msg = 'This email is already taken.';
        return false;
    }
    if(!(isset($email) && isset($fname) && isset($lname) && isset($pass) && filter_var($email, FILTER_VALIDATE_EMAIL))){
        $this->msg = 'Inesrt all valid requered fields.';
        return false;
    }

    $pass = $this->hashPass($pass);
    $confCode = $this->hashPass(date('Y-m-d H:i:s').$email);
    $stmt = $pdo->prepare('INSERT INTO users (fname, lname, email, password, confirm_code) VALUES (?, ?, ?, ?, ?)');
    if($stmt->execute([$fname,$lname,$email,$pass,$confCode])){
        if($this->sendConfirmationEmail($email)){
            return true;
        }else{
            $this->msg = 'confirmation email sending has failed.';
            return false; 
        }
    }else{
        $this->msg = 'Inesrting a new user failed.';
        return false;
    }
}

And Here is password hashing:这是密码散列:

private function hashPass($pass){
    return password_hash($pass, PASSWORD_DEFAULT);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM