Home  >  Article  >  Backend Development  >  How to deal with PHP login failure

How to deal with PHP login failure

藏色散人
藏色散人Original
2021-03-19 09:14:384379browse

How to handle PHP login failure: First create a table to record user login information; then query the user_login_info table to see if there are any records related to password errors in the last 30 minutes; then count whether the total number of records reaches the set value. A certain number of errors; finally set a limit on the number of login password errors.

How to deal with PHP login failure

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

PHP implements login failure limit

Limit on the number of incorrect login passwords

The importance of security to every website is self-evident. Among them, login is a place in the website that is more vulnerable to attacks, so how can we enhance the security of the login function?

Let’s first look at how some well-known websites do it

Github

The same account on the Github website uses the same IP address to enter the password continuously. After a certain number of mistakes, the account will be locked for 30 minutes.

The main reason why Github does this, I think, is mainly based on the following considerations:

Prevent users’ account passwords from being violently cracked

Implementation ideas

Since the login function of so many websites has this function, how to implement it specifically. Let’s talk about it in detail below.

Idea

A table (user_login_info) is needed to record user login information, whether the login is successful or failed. And it needs to be able to distinguish whether the login failed or succeeded.

Every time you log in, first query from the user_login_info table whether there are any records of related password errors in the last 30 minutes (assuming here that after the number of password errors reaches 5 times, the user will be disabled for 30 minutes), and then count the total number of records Whether the number of items reaches the set number of errors.

If the same user under the same IP reaches the set number of incorrect passwords within 30 minutes, the user will not be allowed to log in.

[Recommended: PHP video tutorial]

Specific code and table design

Table Design

user_login_info table

   CREATE TABLE `user_login_info` (
       `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT  NOT NULL,
       `uid` int(10) UNSIGNED NOT NULL,
       `ipaddr` int(10) UNSIGNED NOT NULL COMMENT '用户登陆IP',
       `logintime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 
       COMMENT '用户登陆时间',
       `pass_wrong_time_status` tinyint(10) UNSIGNED NOT NULL COMMENT '登陆密码错误状态' 
       COMMENT '0 正确 2错误'
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
user表(用户表)
   CREATE TABLE `user` (
      `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
      `name` varchar(100) NOT NULL COMMENT '用户名',
      `email` varchar(100) NOT NULL,
      `pass` varchar(255) NOT NULL,
      `status` tinyint(3) UNSIGNED NOT NULL DEFAULT '1' COMMENT '1启用 2禁用',
       PRIMARY key(id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
核心代码
<?php
 
class Login
{
 
    protected $pdo;
 
    public function __construct()
    {
        //链接数据库
        $this->connectDB();
    }
 
    protected function connectDB()
    {
        $dsn = "mysql:host=localhost;dbname=demo;charset=utf8";
        $this->pdo = new PDO($dsn, &#39;root&#39;, &#39;root&#39;);
    }
 
    //显示登录页
    public function loginPage()
    {
          include_once(&#39;./html/login.html&#39;);
 
    }
 
    //接受用户数据做登录
    public function handlerLogin()
    {
 
        $email = $_POST[&#39;email&#39;];
        $pass = $_POST[&#39;pass&#39;];
 
        //根据用户提交数据查询用户信息
        $sql = "select id,name,pass,reg_time from user where email = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$email]);
 
        $userData = $stmt->fetch(\PDO::FETCH_ASSOC);
 
        //没有对应邮箱
        if ( empty($userData) ) {
 
            echo &#39;登录失败1&#39;;
 
            echo &#39;<meta http-equiv="refresh" content="2;url=./login.php">&#39;;
            exit;
        }
 
        //检查用户最近30分钟密码错误次数
        $res = $this->checkPassWrongTime($userData[&#39;id&#39;]);
 
        //错误次数超过限制次数
        if ( $res === false ) {
            echo &#39;你刚刚输错很多次密码,为了保证账户安全,系统已经将您账号锁定30min&#39;;
 
            echo &#39;<meta http-equiv="refresh" content="2;url=./login.php">&#39;;
            exit;
        }
 
 
        //判断密码是否正确
        $isRightPass = password_verify($pass, $userData[&#39;pass&#39;]);
 
        //登录成功
        if ( $isRightPass ) {
 
            echo &#39;登录成功&#39;;
            exit;
        } else {
 
            //记录密码错误次数
            $this->recordPassWrongTime($userData[&#39;id&#39;]);
 
            echo &#39;登录失败2&#39;;
            echo &#39;<meta http-equiv="refresh" content="2;url=./login.php">&#39;;
            exit;
        }
 
    }
 
    //记录密码输出信息
    protected function recordPassWrongTime($uid)
    {
 
        //ip2long()函数可以将IP地址转换成数字
        $ip = ip2long( $_SERVER[&#39;REMOTE_ADDR&#39;] );
 
        $time = date(&#39;Y-m-d H:i:s&#39;);
        $sql = "insert into user_login_info(uid,ipaddr,logintime,pass_wrong_time_status) values($uid,$ip,&#39;{$time}&#39;,2)";
 
 
        $stmt = $this->pdo->prepare($sql);
 
        $stmt->execute();
    }
 
    /**
     * 检查用户最近$min分钟密码错误次数
     * $uid 用户ID
     * $min  锁定时间
     * $wTIme 错误次数
     * @return 错误次数超过返回false,其他返回错误次数,提示用户
     */
    protected function checkPassWrongTime($uid, $min=30, $wTime=3)
    {
 
        if ( empty($uid) ) {
 
            throw new \Exception("第一个参数不能为空");
 
        }
 
        $time = time();
        $prevTime = time() - $min*60;
 
        //用户所在登录ip
        $ip = ip2long( $_SERVER[&#39;REMOTE_ADDR&#39;] );
 
 
        //pass_wrong_time_status代表用户输出了密码
        $sql = "select * from user_login_info where uid={$uid} and pass_wrong_time_status=2 and UNIX_TIMESTAMP(logintime) between $prevTime and $time and ipaddr=$ip";
 
        $stmt = $this->pdo->prepare($sql);
 
        $stmt->execute();
 
        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
 
 
        //统计错误次数
        $wrongTime = count($data);
 
        //判断错误次数是否超过限制次数
        if ( $wrongTime > $wTime ) {
            return false;
        }
 
        return $wrongTime;
 
    }
 
    public function __call($methodName, $params)
    {
 
        echo &#39;访问的页面不存在&#39;,&#39;<a href="./login.php">返回登录页</a>&#39;;
    }
}
 
$a = @$_GET[&#39;a&#39;]?$_GET[&#39;a&#39;]:&#39;loginPage&#39;;
 
 
$login = new Login();
 
$login->$a();

The above is the detailed content of How to deal with PHP login failure. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn