** 用途:
密码输入错误N次后锁住
每天免费抽(红包)奖N此
每小时最多评论N条,每小时最多发帖N条
复杂接口频繁调用限制(每分钟最多调用N次)
**
/**
* 次数限制 用于限制一天内有N次机会,或X秒内有N次机会 优化后使用加法,逻辑更加通畅
* @param $unique_id 唯一标识(用户ID或手机号)
* @param $numberoftimes 最大次数N
* @param $timespant 时间间隔(字符串oneday一天或者过期秒数X)
* @param $verification 是否只做验证false|true
* @return bool|mixed
*/
function limitoftimes($unique_id,$numberoftimes=10,$timespant="oneday",$verification=false){
$cacheneme = request()->url().$numberoftimes.'-'.$unique_id;
$nowtimes = cache($cacheneme);//获取缓存中的当前次数
if($nowtimes>=$numberoftimes)return false;
if($verification)return true;
if($timespant==="oneday"){
$expires_in = strtotime(date('Y-m-d',strtotime('+1 day'))) - time();
}else{
$expires_inname = $cacheneme."-".$timespant;//设置时间缓存名称
$expires_intime = cache($expires_inname);
if($expires_intime){
$expires_in = $timespant-(request()->time() - $expires_intime);
}else{
$expires_in = $timespant;
cache($expires_inname,request()->time(),$expires_in);
}
}
$nowtimes = $nowtimes+1;//不可用++ 因为有false的情况
cache($cacheneme,$nowtimes,$expires_in);
return $numberoftimes-$nowtimes;
}
//调用方法实例
//普通的次数限制直接调用
if(limitoftimes($user_id,3,60)===false)$this->error("检测到您存在恶意刷屏行为,屏蔽一分钟");
//密码验证调用:
//验证时可调用, 其中limitoftimes($user_id,3,"oneday",true)返回的类型有两种种true|false 其中false代表限期内次数用尽
if(limitoftimes($user_id,5,'oneday',true) === 0)$this->error("今日密码输入错误次数超过5次,余额支付已锁定,请明日再试!");
if ($this->auth->password != $this->auth->getEncryptPassword($password, $this->auth->salt)){
$nowtimes = limitoftimes($user_id,5);
if(!$nowtimes)$this->error("今日密码输入错误次数超过5次,余额支付已锁定,请明日再试!");
$this->error("密码不正确,今日还有{$nowtimes}次机会");
}