当前位置:Gxlcms > php框架 > 详解ThinkPHP5实现极验滑动验证码geetest功能

详解ThinkPHP5实现极验滑动验证码geetest功能

时间:2021-07-01 10:21:17 帮助过:77人阅读

下面由thinkphp教程栏目给大家详解ThinkPHP5实现极验滑动验证码geetest功能,希望对需要的朋友有所帮助!

ThinkPHP5实现极验滑动验证码geetest功能

现在很多网站,比如淘宝,京东等都改用使用极验拖动验证码实现登录,这种方式比传统的验证码方式有更好的体验,减少用户输入的错误,也同样能起到防盗刷的功能。现在很多极验都是第三方的,也很多都是收费的。这里主要介绍thinkphp整合系列之极验滑动验证码geetest,官网:http://www.geetest.com

具体如下:

一:注册获取key

注册;创建应用;获取key;

38c0e7adc9293c6e1ecab9b7d39bac3.png

二:导入sdk

/ThinkPHP/Library/Org/Xb/GeetestLip.class.php(此处GeetestLip.class.php是我重新命名的geetest类文件,原名为class.geetestlib.php)

79d0fe58eb63775a84ad09074880891.png

此处牵扯到thinkphp引入第三方类,我把第三方类放到Org/Util/Xb下面了,同时对该类文件加入命名空间如下,否则实例化类时找不到文件

0fa186926fe4c2af43f703703075efa.png

三:生成验证样式

admin/view/public/cdtsh_log_smfyws.php

<!doctype html>
<html>
<head>
  <meta charset="GBK" />
  <title>网站管理系统后台</title>
  <script language="javascript" type="text/javascript" src="__JS__/jquery.js"></script>
  <link rel="stylesheet" href="__CSS__/jquery.validator.css">
  <script type="text/javascript" src="__JS__/jquery.validator.js"></script>
  <script type="text/javascript" src="__JS__/zh_CN.js"></script>
  <link href="__CSS__/admin_login.css?v20130227" rel="stylesheet" />
  <script>
    $(document).ready(function(){
      var verifyimg = $(".verifyimg").attr("src");
      $(".reloadverify").click(function(){
        if( verifyimg.indexOf('?')>0){
          $(".verifyimg").attr("src", verifyimg+'&random='+Math.random());
        }else{
          $(".verifyimg").attr("src", verifyimg.replace(/\?.*$/,'')+'?'+Math.random());
        }
      });
    });
  </script>
</head>
<body>
<p class="wrap">
  <h1><a href="javascript:;" style="height: 116px; width: 250px;">后台管理中心</a></h1>
  <form method="post" action="{:U('Admin/Public/cdtsh_log_smfyws')}">
    <p class="login">
      <ul>
        <li>
          <input class="input" id="username" name="username"type="text" title="用户名" data-rule="required;username" placeholder="用户名" />
          <span class="msg-box n-right" style="position:absolute; left: 248px; top: 12px; " for="username"></span>
        </li>
        <li>
          <input class="input" name="password" type="password" title="密码" data-rule="required;password" placeholder="密码"/>
          <span class="msg-box n-right" style="position:absolute;left: 248px; top: 12px;" for="password"></span>
        </li>
        <li>
          <input class="input" id="verify" name="verify" type="text" style="width:130px;" title="密码" data-ok=" " placeholder="验证码" data-tip="输入验证码!" title="验证码" data-rule="required;text;remote[{:U('Admin/Public/check_verify')}]" />
          <p class="yanzhengma_box" id="verifyshow">  <img class="verifyimg reloadverify" style=" cursor: pointer;" align="right" src="{:U('public/verify')}" title="点击刷新"> </p>
          <span class="msg-box n-right" style="position:absolute;left: 248px; top: 12px;" for="verify"></span>
        </li>
      </ul>
      <ul>
          <!--<input type="button" value="异步验证登录" onclick="check_verify()">-->
          <!--<input type="submit" value="post提交登录">-->
          <p id="captcha"></p>
      </ul>
      <button type="submit" class="btn" id="subbtn">登录</button>
    </p>
  </form>
</p>
<script src="http://static.geetest.com/static/tools/gt.js"></script>
<script>
  var handler = function (captchaObj) {
    // 将验证码加到id为captcha的元素里
    captchaObj.appendTo("#captcha");
   };
  // 获取验证码
  $.get("{:U('Admin/Public/verifys')}", function(data) {
    // 使用initGeetest接口
    // 参数1:配置参数,与创建Geetest实例时接受的参数一致
    // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
    initGeetest({
      gt: data.gt,
      challenge: data.challenge,
      product: "float", // 产品形式
      offline: !data.success,
      new_captcha:'true',
      width:'260px',
    }, handler);
  },'json');
</script>
</body>
</html>

四:验证函数

/Application/Common/Common/function.php

/**
 * geetest检测验证码
 */
function geetest_chcek_verify($data){
  $geetest_id = "7149e2021d7938157e";
  $geetest_key = "62b92039e1e9cf9455";
  $geetest=new \Org\Util\Xb\GeetestLib($geetest_id,$geetest_key);
  $user_id=$_SESSION['geetest']['user_id'];
  $ip_address=$_SESSION['geetest']['ip_address'];
  $dataa = array(
    "user_id" => $user_id, # 网站用户id
    "client_type" => "web", #web:电脑上的浏览器;h5:手机上的浏览器,包括移动应用内完全内置的web_view;native:通过原生SDK植入APP应用的方式
    "ip_address" => $ip_address, # 请在此处传输用户请求验证时所携带的IP
  );
  if ($_SESSION['geetest']['gtserver']==1){
    $result=$geetest->success_validate($data['geetest_challenge'], $data['geetest_validate'], $data['geetest_seccode'], $dataa);
    //return $result;
    if ($result) {
      //return 11;
      return true;
    } else{
      //return 22;
      return false;
    }
  }else{
    if ($geetest->fail_validate($data['geetest_challenge'],$data['geetest_validate'],$data['geetest_seccode'])) {
      //return 33;
      return true;  
    }else{
      //return 44;
      return false;
    }
  }
}
//获取id地址
function GetIP() {
  if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
    $cip = $_SERVER["HTTP_CLIENT_IP"];
  } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  } elseif (!empty($_SERVER["REMOTE_ADDR"])) {
    $cip = $_SERVER["REMOTE_ADDR"];
  } else {
    $cip = "无法获取!";
  }
  return $cip;
}

五:php生成验证码并验证

//极速验证
  public function verifys(){
    //require_once dirname(dirname(dirname(__FILE__))) . '/lib/class.geetestlib.php';
    //require_once dirname(dirname(__FILE__)) . '/config/config.php';
    // $GtSdk = new GeetestLib(CAPTCHA_ID, PRIVATE_KEY);
    $geetest_id = "7149e2021d7938157e9";
    $geetest_key = "62b92039e1e9cf";
    $geetest=new \Org\Util\Xb\GeetestLib($geetest_id,$geetest_key);
    //dump($geetest);die;
    $user_id = "test";
    $data = array(
      "user_id" => $user_id, # 网站用户id
      "client_type" => "web", #web:电脑上的浏览器;h5:手机上的浏览器,包括移动应用内完全内置的web_view;native:通过原生SDK植入APP应用的方式
      "ip_address" => GetIP(), # 请在此处传输用户请求验证时所携带的IP
    );
    $status = $geetest->pre_process($data,1);
    //dump($status);
    $_SESSION['geetest']=array(
      'gtserver'=>$status,
      'user_id'=>$user_id,
      'ip_address'=>GetIP(),
      );
    echo $geetest->get_response_str();
  }
 public function cdtsh_log_smfyws() {
    if ($_SESSION['userid']) {
      $this->redirect('Admin/Index/Index');
    } else {
      if (IS_POST) {
        $username = $_POST['username'];
        $password = $_POST['password'];
        //$geetest_challenge = $_POST['geetest_challenge'];
        //$geetest_validate = $_POST['geetest_validate'];
        //$geetest_seccode = $_POST['geetest_seccode'];
        $data=I('post.');
        if($data['geetest_challenge']=="" || $data['geetest_validate']=="" ||$data['geetest_seccode']=="" ){
          $this->error('请进行图形验证');
        }else{
          //dump(geetest_chcek_verify($data));
          if (geetest_chcek_verify($data)){
            //echo '验证成功';
            if ($this->loginAdmin($username, $password)) {
              $data = M("User")->where("username='".$username."' and password='".md5($password)."'")->find();
              if ($data["status"] != 1) {
                //判断是否禁用
                $this->recordLoginAdmin($_POST['username'], $_POST['password'], 0, "账号禁用"); //记录登录日志
                $this->error('该帐号禁用');
              } else {
                $save["lastlogin_time"] = time();
                $save["lastlogin_ip"] = get_client_ip();
                $save["login_num"] = $data["login_num"] + 1;
                $status = M("user")->where(array("id" => $data['id']))->save($save);
                $_SESSION['userid'] = $data['id'];
                $_SESSION['user'] = $data['username'];
                $_SESSION['rid'] = $data['a_Id'];
                $this->recordLoginAdmin($_POST['username'], $_POST['password'], 1); //记录登录日志
                $this->redirect('Admin/Index/Index');
                //$this->success('登录成功',U('Admin/Index/Index'));
              }
            } else {
              $this->recordLoginAdmin($_POST['username'], $_POST['password'], 0, "账号密码错误"); //记录登录日志
              $this->error('登录失败');
            }
          }else{
            //echo '图形验证失败';
            $this->error('图形验证失败');
          }
        }
      } else {
        $this->display();
      }
    }
  }

效果图如下:

登录页面

a75063c1020ba215298b2a47b5090ed.png

点击验证后

ff50b13bc2d3e6305e3a367c9a95eef.png

以上就是详解ThinkPHP5实现极验滑动验证码geetest功能的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行