php限制登录次数

<?php
//mysql 字段验证
require 'connect.php';
$username = $_POST['username'];
$password = $_POST['password'];

//检查用户是否存在
$row = $mysql->query("select * from user where username=$username limit 1");
$time = time();
if (empty($row['err_time'])) {
    //err_time为空,直接进行密码校验
    $login = $mysql->query("select * from user where username=$username and password=$password limit 1");
    if ($login) {
        echo '登录成功,设置跳转';
    } else {
        $count = $login['err_count'];
        $mysql->query("UPDATE user SET err_time=$time,err_count=$count+1 where username=$username");
       echo "登录失败";
    }
} else {
    //如果err_time不为空
    $err_time = $login['err_time'];
    $hour = $hour = floor(($time - $err_time) % 86400 / 3600); //计算时间差
    $count = $login['err_count'];
    if ($hour < 24) {
        if($count <= 3){
            $mysql->query("UPDATE user SET err_time=$time,err_count=$count+1 where username=$username");
            echo "登录失败";
        }else{
            //24小时以内,错误次数大于3 账户冻结
            echo '您的账户已经被冻结,请联系网站管理员'; 
            exit;
        }
    } else {
        //大于24小时,自动解除冻结,重置err_time和err_count的值
        $mysql->query("UPDATE user SET err_time=null,err_count=0 where username=$username");
        $login = $mysql->query("select * from user where username=$username and password=$password limit 1");
        if ($login) {
            echo '登录成功,设置跳转';
        } else {
            //解除冻结后,账号密码错误的情况,更新数据库,返回登录页
            $count = $login['err_count'];
            $mysql->query("UPDATE user SET err_time=$time,err_count=$count+1 where username=$username");
            echo "登录失败";
        }
    }
}
<?php
//redis方法
$username = 'username';
$password = 'password';

$pwd =123456;

$redis = new Redis;
$redis->connect('127.0.0.1',6379);
$numData = $redis->get($username);
if($numData>3){
    echo '登录错误次数超过三次';
    exit();
}
if($password !=$pwd){
    $redis->incr($username);
    //20s重置
    $redis->setTimeout($username,20);
    echo '登录失败';
}else{
    echo '登录成功';
}

 

posted @ 2020-07-22 10:34  za_szybko  阅读(1140)  评论(0编辑  收藏  举报