使用Vue和PHP 实现验证码功能

PHP

<?php

//因为前端axios的数据格式问题,使用post方式传递时必须要下面这个代码
$v=(file_get_contents("php://input"));
$c=json_decode($v,true);
// var_dump(json_decode($v,true));
//关闭错误提示,因为作者把两个功能放在一个文件处理了  当使用一个功能时另外一个的参数收不到会报错。
ini_set('display_errors','off');
//开启session
session_start();
//发送的绑定的邮箱,

//这个是“发送邮箱功能”的用户绑定的邮箱
$contactmail=$c['contact'];
//用户登录后用来辨别的邮箱 因为两个功能放在一起了,其实上下是两个变量内容是一样的,只是为了防止参数导致登录的时候会发送邮件
//应该在点击发送验证码的时候才登录邮件。
//这里是第二个功能 所以区分,因为两个都是一样的 避免不必要麻烦
$mail=$c['mail'];
//第二个功能 用户输入的验证码。
$usercode=$c['code'];
// 引入PHPMailer的核心文件   如果不引入是使用不了邮箱功能的, 安装包可以在github上搜索PHPmailer star数最多的就是
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require './phpmailer/Exception.php';
require './phpmailer/PHPMailer.php';
require './phpmailer/SMTP.php';
//正则一下。 获得括号内的内容
function destroy($str)
{
$result = array();
preg_match_all("/(?:\()(.*)(?:\))/i",$str, $result);
return $result[1][0];
};
//判断是否有输入验证码。
if(($usercode)){
if($_SESSION[`$mail`]){
$allStr=$_SESSION[`$mail`];
$destroyTime=destroy($allStr);
if($destroyTime<time()){
    unset($_SESSION[`$mail`]);
    echo "验证码已经过期";
}else{
    //获取括号外的验证码。 因为这边发送的验证码为了区分用户和验证码的格式是这样的 (123456@qq.com)1254 括号内的是绑定的邮箱外边的是验证码
   $code = preg_replace( '/\((.*)\)/', '',$allStr);
    if($usercode===$code){
        echo "验证码正确";
    }
}
}else{
    echo "请重新获取验证码";
}
};


if(isset($contactmail)){
$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //服务器配置
    $mail->CharSet ="UTF-8";                     //设定邮件编码
    $mail->SMTPDebug = 0;                        // 调试模式输出
    $mail->isSMTP();                             // 使用SMTP
    $mail->Host = 'smtp.qq.com';                // SMTP服务器
    $mail->SMTPAuth = true;                      // 允许 SMTP 认证
    $mail->Username = '13232@qq.com';                // SMTP 用户名  即邮箱的用户名
    $mail->Password = 'zalcdssrd111nwnhrchhdd';             // SMTP 密码  部分邮箱是授权码(例如163邮箱)
    $mail->SMTPSecure = 'ssl';                    // 允许 TLS 或者ssl协议
    $mail->Port = 465;                            // 服务器端口 25 或者465 具体要看邮箱服务器支持

    $mail->setFrom('15000@qq.com','你好' );  //发件人
    $mail->addAddress($contactmail, 'Joe');  // 收件人
    //$mail->addAddress('ellen@example.com');  // 可添加多个收件人
    $mail->addReplyTo('15000@qq.com', 'info'); //回复的时候回复给哪个邮箱 建议和发件人一致
    //$mail->addCC('cc@example.com');                    //抄送
    //$mail->addBCC('bcc@example.com');                    //密送

    //发送附件
    // $mail->addAttachment('../xy.zip');         // 添加附件
    // $mail->addAttachment('../thumb-1.jpg', 'new.jpg');    // 发送附件并且重命名

    //Content
//随机验证码
    $code=rand(10000,99999);
    $mail->isHTML(true);                                  // 是否以HTML文档格式发送  发送后客户端可直接显示对应HTML内容
    $mail->Subject = '重要!如果不是您的操作,请不要理会!';
    $mail->Body    = '<h1>您好,您的验证码是:</h1><br/>'.'<h1>'.$code.'</h1>'.'<h2>(1分钟内有效,请不要告诉任何人!)</h2> <br/>' . '<h3>发送时间</h3>'.date('Y-m-d H:i:s');
    $mail->AltBody = '如果邮件客户端不支持HTML则显示此内容';

    $mail->send();
//设置session过期时间
    $time=time()+60;
//格式=(邮箱)验证码
    $_SESSION[`$contactmail`]='('.$time.')'.$code;
} catch (Exception $e) {
    // echo '邮件发送失败: ', $mail->ErrorInfo;
}
}

Vue

HTML

                <b-col style="padding-right:15px padding-left:0px">
                  <b-button
                    style="margin:0px ;width:100%"
                    variant="info"
                    @click="countDown"
                    id="sendBtn"
                    v-show="codeBtnShow"
                  >获取验证码</b-button>
                  <b-button
                    style="margin:0px ;width:100%"
                    variant="info"
                    @click="countDown"
                    id="sendBtn"
                    disabled
                    v-show="!codeBtnShow"
                  >{{count}}后重新获取</b-button>
                </b-col>
  <span class="errorTips" v-if="infoTips">您的账号是{{this.username}}密码是:{{this.userpass}}</span>
<b-button type="submit" variant="primary" @click="Myuser" v-if="!findBtn">确认</b-button>

Vue

data(){
return{
 code: "",
 timer: null,
 findBtn: true,
form: {
        name: "",
        userpass: "",
        code: ""
      },
}
      //存储的账号和密码
      username: "",
      userpass: "",
}

methods:{

//找回密码的功能
 Myuser: function() {
      // alert(JSON.stringify(this.form));
      if (
        this.form.code != "" &&
        this.form.code != null &&
        this.form.code != undefined
      ) {
//验证账号密码的api 如果验证成果返回账号密码
        verify(this.contact, this.form.code).then(res => {
           this.code=res.data;
                   if(this.code==='验证码正确'){
           myPass(this.form.name).then(res => {
          this.username = res.data[0].username;
          this.userpass = res.data[0].userpass;
          // console.log(this.username, this.userpass);
          this.infoTips = true;
        });
        }else{
          alert("验证码错误!");
        }
        });

      }

    },


//发送验证码 外加定时器
    countDown() {
      const TIME_COUNT = 60;
      //当点击的一瞬间disabled
      this.codeBtnShow = false;
//发送验证码的api
      sendMail(this.contact).then(res => {
        // this.code = res.data;
      });
      if (!this.timer) {
        this.count = TIME_COUNT;
        //发送
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.codeBtnShow = true;
            //清除定时器
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      } else {
      }
    },
}







封装后的api

export const sendMail=(contact)=>requests({

  method:"post",
  url:"/personnelInfo/users/sendMail.php",
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  data:{
    contact,
  }
})
export const verify=(mail,code)=>requests({

  method:"post",
  url:"/personnelInfo/users/sendMail.php",
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  data:{
    mail,
    code,
  }
})
export const myPass=(username)=>requests({

  method:"post",
  url:"/personnelInfo/users/mypass.php",
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  data:{
    username,
  }
})

效果

当过期时 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值