search
HomeBackend DevelopmentPHP TutorialPHP extreme verification code example explanation

You can find this article, which means you are no longer completely unfamiliar with Jiexian verification. I won’t go into all the nonsense and just start explaining how to use it. But before that, paste a few The URL you may use:

Official website: http://www.geetest.com/

Official document: http://www.geetest.com/install/sections/idx -basic-introduction.html

github:https://github.com/GeeTeam/gt-php-sdk.git

How to use:

First To confirm the front-end usage page, such as the login page


 

1. Access the imported class library on the login page:

If your website uses https, you only need to change the place where Jiqianku is introduced to the https protocol, and there is no need to change other places. For example, replace it with the following code:


 

2. Initialize the front end

The following code It needs to be executed after the page is loaded. If you use jQuery, you can write it in $(function(){});

$.ajax({
  // 获取id,challenge,success(是否启用failback)
  url: "../web/StartCaptchaServlet.php?t=" + (new Date()).getTime(), // 加随机数防止缓存
  type: "get",
  dataType: "json",
  success: function (data) {
    // 使用initGeetest接口
    // 参数1:配置参数
    // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
    initGeetest({
      gt: data.gt,
      challenge: data.challenge,
      product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
      offline: !data.success // 表示用户后台检测极验服务器是否宕机,与SDK配合,用户一般不需要关注
    }, handlerPopup);
  }
});

The above code means that after the page is loaded, you need to go to the URL you specified. Obtain the verification code information on the address. As for what is written in the above URL address "../web/StartCaptchaServlet.php", we will explain this in detail in the server-side code deployment.

But it should be noted that there is a callback function called "handlerPopup" in the above code. This function is the real initialization code you need to verify the code: as follows:

// 代码详细说明
var handlerPopup = function (captchaObj) {
  // 注册提交按钮事件,比如在登陆页面的登陆按钮
  $("#popup-submit").click(function () {
    // 此处省略在登陆界面中,获取登陆数据的一些步骤
     
    // 先校验是否点击了验证码
    var validate = captchaObj.getValidate();
    if (!validate) {
      alert('请先完成验证!');
      return;
    }
    // 提交验证码信息,比如登陆页面,你需要提交登陆信息,用户名和密码等登陆数据
    $.ajax({
      url: "../web/VerifyLoginServlet.php",
      type: "post",
      // dataType: "json",
      data: {
        // 用户名和密码等其他数据,自己获取,不做演示
        username:username,
        password:password,
        // 验证码数据,这些数据不用自己获取
        // 这是二次验证所需的三个值
        // 当然,你也可以直接设置验证码单独校验,省略其他信息
        geetest_challenge: validate.geetest_challenge,
        geetest_validate: validate.geetest_validate,
        geetest_seccode: validate.geetest_seccode
      },
      // 这里是正确返回处理结果的处理函数
      // 假设你就返回了1,2,3
      // 当然,正常情况是返回JSON数据
      success: function (result) {
        // 1表示验证码验证失败
        if (result == "1") {
          alert("验证码验证失败!");
        }else if (result == "2") {
          alert("用户名或密码错误!");
        }else if (result == "3") {
          alert("登陆成功!");
          // 登陆成功了,可以在这里做其他处理
        }else{
          alert("登陆错误!");
        }
      }
    });
  });
  // 弹出式需要绑定触发验证码弹出按钮
  // 比如在登陆页面,这个触发按钮就是登陆按钮
  captchaObj.bindOn("#popup-submit");
    
  // 将验证码加到id为captcha的元素里
  // 验证码将会在下面指定的元素中显示出来
  captchaObj.appendTo("#popup-captcha");
    
  // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
  

At this point, the front-end All settings have been written, official documentation: http://www.geetest.com/install/sections/idx-client-sdk.html

3. Server-side deployment (PHP)

In the first step, we set up such an address "../web/StartCaptchaServlet.php", what to write in this address:

<?php
// 引入文件
require_once dirname(dirname(__FILE__)) . &#39;/lib/class.geetestlib.php&#39;;
require_once dirname(dirname(__FILE__)) . &#39;/config/config.php&#39;;
// 实例化,实例化的参数在config中配置,分别是:验证ID 和 验证Key,如何获取下面会说。
$GtSdk = new GeetestLib(CAPTCHA_ID, PRIVATE_KEY);
session_start();
// 这个是用户的标识,或者说是给极验服务器区分的标识,如果你项目没有预先设置,可以像下面这样设置:
if(!isset($_SESSION[&#39;user_id&#39;])){
  $_SESSION[&#39;user_id&#39;]=uniqid();// 生成一个唯一ID
}
$user_id = $_SESSION[&#39;user_id&#39;];
// 或者,你就直接写成:
// $user_id = "test";
  
// 生成验证码信息,并返回给客户端
$status = $GtSdk->pre_process($user_id);
$_SESSION[&#39;gtserver&#39;] = $status;
$_SESSION[&#39;user_id&#39;] = $user_id;
echo $GtSdk->get_response_str();
?>
  

How to get the verification ID and verification Key:

1. Register an account from the verification background
2. Add verification, you can get a set of currently verified ID/Key
3. Replace the ID and Key to captcha_id/ in the config.php file. The value of the private_key variable

4. Server-side verification (secondary verification) after clicking the submit button

For example, as mentioned above, when the user logs in, you put the user name, password and verification code information All have been submitted to the server. At this time, you can do verification:

<?php
// 引入文件
require_once dirname(dirname(__FILE__)) . &#39;/lib/class.geetestlib.php&#39;;
require_once dirname(dirname(__FILE__)) . &#39;/config/config.php&#39;;
session_start();
$GtSdk = new GeetestLib(CAPTCHA_ID, PRIVATE_KEY);
  
// 比如你设置了一个验证码是否验证通过的标识
$code_flag=false;
  
// 这里获取你之前设置的user_id,传送给极验服务器做校验
$user_id = $_SESSION[&#39;user_id&#39;];
if ($_SESSION[&#39;gtserver&#39;] == 1) {
  $result = $GtSdk->success_validate($_POST[&#39;geetest_challenge&#39;], $_POST[&#39;geetest_validate&#39;], $_POST[&#39;geetest_seccode&#39;], $user_id);
  if ($result) {
    // 验证码验证成功
    $code_flag=true;
  }
}else{
  if ($GtSdk->fail_validate($_POST[&#39;geetest_challenge&#39;],$_POST[&#39;geetest_validate&#39;],$_POST[&#39;geetest_seccode&#39;])) {
     // 验证码验证成功
    $code_flag=true;
  }
}
  
// 如果验证码验证成功,再进行其他校验
if($code_flag){
  // 其他验证操作
  // 用户名不对时,返回2,其他错误返回3,等等。。。。
}else{
  // 验证码验证失败,返回1,这里和上面相呼应,当然我的项目没有简单的返回1,而是返回了JSON数据
  echo 1;
  exit(-1);
}
?>
  

Thank you for reading, I hope it can help everyone, thank you everyone for your support of this site!

For more relevant articles on PHP’s extreme verification code examples, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment