更改配置文件 app.php 里添加
//前端模块
'default_module' =>'home',
在config文件下cache.php里面去添加redis配置
// 缓存连接方式配置
'stores' => [
'file' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => '',
// 缓存前缀
'prefix' => '',
// 缓存有效期 0表示永久缓存
'expire' => 0,
// 缓存标签前缀
'tag_prefix' => 'tag:',
// 序列化机制 例如 ['serialize', 'unserialize']
'serialize' => [],
],
// 更多的缓存连接
'redis' => [
// 驱动方式
'type' => 'redis',
// 服务器地址
'host' => '127.0.0.1',
'port' =>'6379',
'expire' =>60,
],
],
在小p里开启redis
前端点击发送验证码要做手机号的验证和调后台发送短信的接口
前端:短信验证码的时间限制(频率) + 手机号的验证
<script>
$(function () {
//验证手机号
$('#dyMobileButton').click(function () {
// 获取手机号
var phone = $('#phone').val();
if (phone == ''){
$('#phone').next().html('手机号不能为空');
return;
}else if (!/^1[3-9]\d{9}$/.test(phone)){
$('#phone').next().html('手机号格式不正确');return;
}else {
$('#phone').next().html('');
}
// 发送短信的时间限制
var time =60;
// 设置定时器
var timeer= setInterval(function () {
time--;
//倒计时
if (time>0){
$('#dyMobileButton').html('还有' + time + '秒');
$('#dyMobileButton').prop('disabled',true);
}else {
$('#dyMobileButton').html('发送验证码');
$('#dyMobileButton').prop('disabled',false);
clearInterval(timeer)
}
}, 1000)
// 请求接口
$.ajax({
"url":"{:url('home/login/sendCode')}",
"type":"post",
"data":"phone=" + phone,
"dataType":"json",
"success":function (res) {
// 提示
alert(res.msg);return;
}
});
})
// 注册 提交注册表单
$('#reg_btn').click(function () {
$('form').submit();
})
})
</script>
后端短信验证
// 发送短信验证的接口
public function sendCode()
{
$param = input();
$phone=$param['phone'];
// 调用第三方的服务
// 生成4位到6位的随机数
$begin_time=time();
$last_time=\think\facade\Cache::store('redis')->get('register_time_'.$param['phone']);
if ($begin_time - $last_time < 60){
$res = [
'code'=>202,
'msg' => '请求次数太多',
];
echo json_encode($res);die;
}
$code =mt_rand(1111,9999);
$smsapi = "http://api.smsbao.com/";
$user = "xing_meng"; //短信平台帐号
$pass = md5("123456789"); //短信平台密码
$content="短信宝发送给你{$code},请不要告诉他人";//要发送的短信内容
$sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
$result =file_get_contents($sendurl) ;
if ($result == 0){
// 发送成功
// 验证码时间限制,单位时间过期
\think\facade\Cache::store('redis')->set('register_code_'.$param['phone'],$code,60);
\think\facade\Cache::store('redis')->set('register_time_'.$param['phone'],time());
$res=[
'code' =>200,
'msg' =>'短信发送成功',
'data'=>$code
];
echo json_encode($res);
die();
}else{
$res=[
'code'=>201,
'msg'=>'短信发送失败',
'data'=>$code
];
echo json_encode($res);die();
}
}
//手机号注册