美文网首页
基于laravel的验证码验证方式

基于laravel的验证码验证方式

作者: 骆旺达 | 来源:发表于2019-02-21 16:50 被阅读0次

基于laravel的验证码验证方式

1、腾讯云手机短信验证

微信截图_20190224231654.png

(1)登录腾讯云-云通信,办理好相关手续,及安装配置

1550737185450.png

sdk配置如下:

qcloudsms_php 采用 composer 进行安装,要使用 qcloudsms 功能,只需要在 composer.json 中添加如下依赖:

{
    "require": {
    "qcloudsms/qcloudsms_php": "0.1.*"
    }
}

然后,更新composer,下载几分钟

composer update 

(2)在.env配置文件中,添加如下参数

QCLOUD_SMS_APP_ID=短信备案appid
QCLOUD_SMS_APP_KEY=短信备案秘钥
QCLOUD_SMS_SIGN=短信备案短信签名

(3)在config文件夹中,创建sms.php文件,写入下面代码,用于返回.env中数据

<?php


return [
    'app_id' => env('QCLOUD_SMS_APP_ID',''),
    'app_key' => env('QCLOUD_SMS_APP_KEY',''),
    'smsSign' => env('QCLOUD_SMS_SIGN','')
];

(4)在控制器中,新建控制函数

function SendMsg(Request $request){

        // 参数1000-9999的随机数
        $code = mt_rand(1000,9999);
        $code = str_pad($code,4,0,STR_PAD_RIGHT);
        $phone = $request->get('phone');
        
        // 发送手机短信
        try{
            $this->sms = config('sms');
            $sender = new SmsSingleSender($this->sms['app_id'],$this->sms['app_key']);
            $templateId = '模板号';
            $result = $sender->sendWithParam(
                '86',
                $phone,
                $templateId,
                [$code,"60"],
                $this->sms['smsSign'],
                "",
                ""
            );
            
            //返回发送结果
            $rsp = json_decode($result,true);
            if($rsp['result']==0){
                return "{
                  \"status\":0,
                  \"result\":\"logo\"
                }";
            }else{
                dd($rsp);
            }

        }catch (Exception $e){
            return self::error(4025,$e);
        }


    }

(5) 创建路由,调用该函数发送短信

Route::any('SendMsg',['uses'=>'cbec@SendMsg']);

(6)前端代码

<div class="layui-inline iphone">
    <div class="layui-input-inline">
      <i class="layui-icon layui-icon-cellphone iphone-icon"></i>
      <input type="tel" name="phone" id="phone" lay-verify="required|phone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-inline veri-code">
    <div class="layui-input-inline">
      <input id="pnum" type="text" name="pnum" lay-verify="required" placeholder="请输入验证码" autocomplete="off" class="layui-input">
      <input type="button" class="layui-btn" id="find"  value="验证码" /> 
    </div>
  </div>
</div>

(7)前端脚本代码

<script type="text/javascript">
   layui.config({
      base: 'static/js/util' //你存放新模块的目录,注意,不是layui的模块目录
    }).use(['jquery','form'],function(){
        var $ = layui.$,form = layui.form;

        $("#find").click(function() {
            if(!/^1\d{10}$/.test($("#phone").val())){
              layer.msg("请输入正确的手机号");
              return false;
            }
            var obj=this;
            $.ajax({
                type:"get",
                url:"{{url('SendMsg')}}?phone="+$("#phone").val(),
                dataType:"json",//返回的
                success:function(data) {
                    if(data.result){
                        $("#find").addClass(" layui-btn-disabled");
                        $('#find').attr('disabled',"true");
                        settime(obj);
                        $("#msg").text(data.msg);
                    }else{
                        layer.msg(data.msg);
                    }
                },
                error:function(msg) {
                    console.log(msg);
                }
            }); 
        })
        var countdown=60; 
        function settime(obj) { 
        if (countdown == 0) { 
            obj.removeAttribute("disabled"); 
            obj.classList.remove("layui-btn-disabled")
            obj.value="获取验证码"; 
            countdown = 60; 
            return;
        } else { 
            
            obj.value="重新发送(" + countdown + ")"; 
            countdown--; 
        } 
        setTimeout(function() { 
            settime(obj) }
            ,1000) 
        }
    })
</script>

2、邮箱验证

微信截图_20190224231049.png

(0)在.env中配置邮箱参数

MAIL_DRIVER=smtp
MAIL_HOST=smtp.163.com
MAIL_PORT=465
MAIL_USERNAME=163邮箱账号
MAIL_PASSWORD=163邮箱密码
MAIL_ENCRYPTION=ssl

(1)前端代码

<div class="layui-form-item">
    <div style="display: inline-block;width: 15%;">邮箱</div>
    <div style="display: inline-block;width: 80%;">
        <input type="email" name="password" required lay-verify="required" placeholder="邮箱" value="{{$student['email']}}" autocomplete="off" class="layui-input" disabled="">
    </div>
    <button id="count" class="layui-btn layui-btn-xs" style="margin-left: 16%;margin-top: 1%;" onClick="click1();return false;">发送邮箱</button>

</div>

(2)前端脚本

var time = 30;
function click1(){
    $.ajax({
        url:'{{url('activation')}}',
        data:"id="+"{{$student['id']}}&operate=1",
        type:'post',
        dataType:'text',
        success:function(msg){
            layui.use(['laypage', 'layer'], function() {var layer = layui.layer;
                if(msg=='1'){
                    layer.alert("邮箱发送失败",{title:"Warning",icon:2});
                }else if(msg=='2'){
                    alert("邮箱发送成功");
                }
            });
        }
    })
    getRandomCode();
}

click1();

//倒计时
function getRandomCode() {
    if (time === 0) {
        time = 30;
        $('#count').text("重新发送");
        $("#count").removeAttr("disabled");
        return ;
    } else {
        time--;
        $('#count').text(time+"秒后重新发送");
        $("#count").attr("disabled","disabled");
    }
    setTimeout(function () {
        getRandomCode();
    }, 1000);
}

(3)邮箱模板send_mail.blade.php

<html>
<style>
    *{
        font-family: 微软雅黑;
    }
</style>
<body >
<div style="border:3px solid cornflowerblue;width: 96%;margin: auto auto;">
    <div style="padding: 1% 1% 1% 1%;width: 98%;">
        <h2>亲爱的{{ $user['user_name'] }}:</h2>
        <div>
            <p style="margin-left: 20px;">您好!很高兴您能使用我们提供的邮箱激活服务。</p>
            <p style="margin-left: 20px">感谢您使用此服务,您的  <span style="font-size: 18px;color: red">验证信息为:{{$info}}</span></p>
            <p style="margin-left: 20px">如果服务器尚未响应,一定要换个新版本浏览器再试试哦!</p>
        </div>
    </div>
</div>
</body>
</html>

(4) 发送邮箱

//发送邮箱
if($request->ajax()){
    if($request->input("operate")==1){
        //发送邮箱
        $student = student_info::find(Session::get("user_id"));
        $num = rand(1000,9999);
        $email = $student->email;
        $student->code = $num;
        if($student->save()) {
            Mail::send('send_mail',['user' => $student, 'info' => $num], function ($message) use ($email) {
                $message->subject('HITSZ-哈尔滨工业大学邮箱激活');
                $message->to($email);
            });
            return 2;
        }else{
            return 1;
        }

    }else{
        //验证邮箱信息
        $student = student_info::find(Session::get("user_id"));
        if($student['code']==$request->input("code")&&$student['code']!="0"){
            $student->role=1;
            if($student->save()){
                Session::put("login_ope",1);
                Session::put("login_name",$student->user_name);
                return 1;
            }else{
                return 2;
            }
        }else{
            return 2;
        }
    }
}

3、普通验证


微信截图_20190224231002.png

(1)验证码自动生成

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/20
 * Time: 23:23
 */

session_start();              //必须处于程序的最顶部,会议管理

$image= imagecreatetruecolor(100,30);                    //定义一个长为100,宽为30px大小的图片(默认是黑色)
$bgcolor=imagecolorallocate($image,255,255,255);      //定义白色的颜色参数,生成彩色像素
imagefill($image,0,0,$bgcolor);                            //把彩色像素填充进$image里面,

$captch_code='';                                                               //预先定义captch_code,空字符串
for($i=0;$i<4;$i++){
    $fontsize=6;
    $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
    $data='0123456789';                             //设立一个字典数组
    $fontcontent=substr($data,rand(0,strlen($data)-1),1);            //从substr方法,从字典数组从随机选取一个字符

    $captch_code.=$fontcontent;                                              //将验证信息拼接到$captch_code里面

    $x=($i*100/4)+rand(5,10);
    $y=rand(5,10);

    imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);

}
//
$_SESSION['authcode']=$captch_code;                                       //将验证信息保存在authcode里面

for($i=0;$i<200;$i++){                                                            //设定图片有200个小点
    $pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));//设定点的颜色像素
    imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor);                       //将点内容添加到$image图片上,($image,$x,$y,填充颜色);
}

for($i=0;$i<3;$i++){                                                               //设定图片有3条线
    $linecolor=imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));    //设线的颜色像素
    imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);        //将线添加到图片上,($image,$x1,$y1,$x2,$y2,填充颜色);
}

header('content-type:image/png');                            //输出图片格式content-type:image/png
imagepng($image);
imagedestroy($image);

(2)前台获取验证码

<div class="layui-form-item">
    <div style="display: inline-block;width: 15%;vertical-align: middle">验证码</div>
    <div style="display: inline-block;width: 40%;vertical-align: middle">
        <input type="text" name="code" required lay-verify="required" placeholder="请输入验证码" autocomplete="off" class="layui-input">

    </div>
    <div style="display: inline-block;border: 1px solid #ccc;width: 25%;vertical-align: middle">
        <img id="captch_img" src="{{url("auto_code?r=")}}<?php echo rand();?>" alt="">
    </div>
    <div style="display: inline-block;width: 10%;vertical-align: top">
        <a  href="javascript:void(0)" onclick="change()" style="margin-left: 10px;font-size: 30px;"><i class="layui-icon layui-icon-refresh-3"></i></a>
    </div>
</div>

(3)验证码核对

public function auto_code(Request $request){
    if ($request->isMethod("POST")){
        session_start();
        // 是否注册过账号
        $test_user_id = student_info::where("user_id","=",$request->input("user_id"))->count();
        if($test_user_id>0){
            return 3;
        }
        // 验证码核对
        if($_SESSION['authcode']==$request->input("code")){
            return 2;
        }else{
            return 1;
        }
    }

    return view("auto_code");
}

相关文章

网友评论

      本文标题:基于laravel的验证码验证方式

      本文链接:https://www.haomeiwen.com/subject/zrkdyqtx.html