php
<?php
/**
* Created by PhpStorm.
* User: finejade
* Date: 2023-10-18
* Time: 11:08
*/
session_start();
include_once('header.php');
include_once('connect.php');
include_once('common.php');
include_once('redis.php');
try {
// 常量 用户错误次数记录
define("USER_LOGIN_ERROR_NUM", 'user_login_error_num');
//错误上线,超过明天登录
define("ERROR_COUNT", 5);
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['username']) ? $_POST['password'] : '';
$captcha = isset($_POST['captcha']) ? $_POST['captcha'] : '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ulen = strlen($username);
$plen = strlen($password);
if ($_SESSION ["captcha"] != $captcha) {
return error('图形验证码不正确');
}
if (!preg_match("/^[\w]+$/", $username) || $ulen < 6 || $ulen > 15) {
return error('用户名只能是字母或数字,且长度为6到15个字符');
}
if (!preg_match("/^[\w]+$/", $password) || $plen < 6 || $plen > 15) {
return error('密码只能是字母或数字,且长度为6到15个字符');
}
$sql = sprintf("SELECT id,username,password,salt FROM m_user where `username`='%s' limit 1", $username);
$result = $conn->query($sql);
$arr = [];
if ($result->num_rows <= 0) {
return error('用户名不存在,请核实后重新登陆');
}
$user = $result->fetch_assoc();
if ($redis->exists(USER_LOGIN_ERROR_NUM . '_' . $user['id'])) {
if ($redis->get(USER_LOGIN_ERROR_NUM . '_' . $user['id']) >= ERROR_COUNT) {
return error('您登陆的错误次数已超过' . ERROR_COUNT . '次,请明天再试');
}
};
$pwd = $user['password'];
$sub_time = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();
if ($pwd != encryption($password, $user['salt'])) {
//如果密码不对,则加入redis 密码错误限制,到达5次,则次日才能登录
if ($redis->exists(USER_LOGIN_ERROR_NUM . '_' . $user['id'])) {
$redis->incr(USER_LOGIN_ERROR_NUM . '_' . $user['id']);
} else {
$redis->set(USER_LOGIN_ERROR_NUM . '_' . $user['id'], 1, $sub_time);
}
return error('用户名或密码错误');
}
$user_info = [];
$user_info['id'] = $user['id'];
$user_info['username'] = $user['username'];
$user_info['nickname'] = $user['nickname'];
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['nickname'] = $user['nickname'];
//如果登录成功,删除该用户错误次数限制
$redis->del(USER_LOGIN_ERROR_NUM . '_' . $user['id']);
$conn->close();
return success($user_info, '登录成功');
}
} catch (Exception $exception) {
echo error($exception->getMessage());
}
?>
redis配置文件
php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379); // 连接到Redis
$redis->auth('123456789');
$redis->select(0);