后台:
public function sendCode(){
$prams = input();
$last_time = Cache::store('redis')->get('register_time_time'.$prams['tel']);
if (time() - $last_time < 60){
$res = [
'code'=>500,
'msg'=>"发送太频繁"
];
echo json_encode($res);die;
}
$code = mt_rand(1111,9999);
$smsapi = "http://api.smsbao.com/";
$user = "hsxaizy"; //短信平台帐号
$pass = md5("123456hsx"); //短信平台密码
$content="【创信】你的验证码是:{$code},3分钟内有效!";//要发送的短信内容
$phone = "";//要发送短信的手机号码
$sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
$result =file_get_contents($sendurl) ;
if ($result == 0){
Cache::store('redis')->set('register_time_code'.$prams['tel'],$code,60);
//防止接口重复调用
Cache::store('redis')->set('register_time_time'.$prams['tel'],time(),60);
$res = [
'code'=>200,
'msg'=>'短信发送成功',
'data'=>$code,
];
echo json_encode($res);die;
}else{
$res = [
'code'=>201,
'msg'=>'短信发送失败',
];
echo json_encode($res);die;
}
}
前台:
<table class="table table-striped">
<tr>
<td>手机号</td>
<td><input type="text" name="tel" class="tel"></td>
</tr>
<tr>
<td>验证码</td>
<td>
<input type="text" class="code">
<button id="codes">发送验证码</button>
</td>
</tr>
<tr>
<td>登录密码</td>
<td><input type="text" name="password" class="password"></td>
</tr>
<tr>
<td>确认密码</td>
<td><input type="text" name="pwd" class="pwd"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="完成注册">
</td>
</tr>
</table>
</body>
JS:
$('#codes').click(function () {
var tel = $('.tel').val();
if (tel == ''){
$('.tel').next().html('手机号不能为空');
return;
} else if (!/^1[3-9]\d{9}$/.test(tel)){
$('.tel').next().html('手机号格式不正确');
return;
} else{
$('.tel').next().html('');
}
var time = 60;
var timer = setInterval(function () {
time--;
if (time > 0){
$('#codes').html('重新发送:'+time+'秒');
$('#codes').prop('disabled',true);
} else{
$('#codes').html('发送验证码');
$('#codes').prop('disabled',false);
clearInterval(timer);
}
},1000);
$.ajax({
url:'/sendCode',
type:'post',
data:{tel:tel},
dataType:'json',
success:function (res) {
alert(res.msg);return
}
})
})