search
HomeBackend DevelopmentPHP ProblemHow to deal with PHP login failure

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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft