thinkphp5下简单操作redis(redis计数器)
php想要操作redis,需要安装redis的php拓展
window下拓展安装
http://pecl.php.net/package/redis 注意下面几个参数 下载对应的版本
下载后将php_redis.dll放到php拓展下
然后修改php.ini 配置文件 拓展名不要写错了,然后重启服务,再看phpinfo,ok成功
php代码操作
php安装好redis拓展,就相当于有用一个redis操作类,通过对应的属性方法,进行操作即可。
在thinkphp5下使用
redis计数器实列
业务需求:
网站用户被输入错误密码次数到一定限制之后,就不允许在尝试登录。
- 为了用户的账户安装
- 防止有人恶意攻击服务器
实现步骤:
登录错误之后,需要记录一下次数,如果超过,就不去验证密码和用户的正确性了。直接不给请求
<?php
namespace app\index\controller;
use think\cache\driver\Redis;
class Index extends \think\Controller
{
public function index()
{
return $this->fetch('test');
}
public function test()
{
//获取用户提交的用户名和密码
$username = input('username');
$password = input('password');
//用户存在数据库的密码
$pwd = '123456';
$redis = new Redis();
$numData = $redis->get($username);
if($numData > 3){
echo '登录次数超过3次';
exit();
}
if($password != $pwd){
//登录失败进行计数操作,key为用户名这里认为是唯一值,value就是错误次数
$redis->inc($username);
//20秒内错误3次就会被提示
$handler = $redis->handler(); //TP5里想用redis的高级方法需要这么用 返回句柄对象,可执行其它高级方法
$handler->setTimeout($username,20); //设置过期时间
echo '登录失败';
}else{
echo '登录成功';
}
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/index/test" method="post">
用户名:<input type="text" name="username">
密码:<input type="text" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>