TP5发送短信限制
<?php //发送手机验证码 function smsCode() { //dump($this->request->post()); //请求方式验证 /*if (!$this->request->isAjax()) { $this->error('请求异常'); }*/ $mobile = $this->request->post('data.mobile'); //dump($mobile);die; $pattern = "/^1[3456789]{1}\d{9}$/"; //手机号不能为空 if (empty($mobile) || !preg_match($pattern, $mobile)) { $this->error('请输入正确的手机号'); } $lastSendtime = Db::name('mscode')->where('mobile', $mobile)->order('id desc')->value('sendtime'); //1分钟只能发一次 if ($lastSendtime && time() - $lastSendtime < 60) { $this->error('发送过于频繁'); } $where = []; $where['sendtime'] = ['gt', strtotime(date('Y-m-d'))]; $send_sum = $sendResult = Db::name('mscode')->where($where)->count(); //一天内平台只能发送300条短信 if ($send_sum > 300) { $this->error('请稍后重试。。。'); } $where['mobile'] = $mobile; $sendResult = Db::name('mscode')->where($where)->count(); //同一手机一天只能发送5条短信 if ($sendResult >= 5) { $this->error('短信超过限制'); } $ip = $this->request->ip(); //需要引入think\Cache类,也可以存数据库; if (cache($ip)) { Cache::inc($ip); } else { cache($ip, 1, 86400); } //同一ip一天只能发送30条短信 if (cache($ip) && cache($ip) > 30) { $this->error('短信超过限制'); } //存入数据库记录 $code = rand(111111, 999999); $data['mobile'] = $mobile; $data['code'] = $code; $data['sendtime'] = time(); $data['state'] = 0; $data['endtime'] = time() + 600; $sendResult = Db::name('mscode')->insert($data); if ($sendResult) { //调用短信发送接口 $result = (new Duanxin())->duanx($mobile, $code); if ($result['status'] == 1) { $this->success('发送成功'); } } $this->error('发送失败'); } /** * 手机验证码验证 * @param $mobile * @param $code * @return array */ function checkCode($mobile, $code) { $mscode = Db::name('mscode'); $rs = array(); //获得最新短信验证码 $codeInfo = $mscode->where(array('mobile' => $mobile))->order('id desc')->find(); if ($codeInfo['code'] != $code) { $rs['state'] = 0; $rs['msg'] = '短信验证码有误'; return $rs; } //判断是否过期 if ($codeInfo['endtime'] < time()) { $rs['state'] = 0; $rs['msg'] = '短信验证码已过期'; return $rs; } //成功返回 $rs['state'] = 1; return $rs; }