Cách tích hợp "No CAPTCHA reCAPTCHA" vào Trang web của bạn (ok)

Đọc thêm: https://app.gitbook.com/@wordpress-lionel/s/project/recaptcha-v2-for-contact-form-7-ok

Đã thực hành :)

Thư viện php họ dùng trong bài biết này :_

C:\Users\Administrator\AppData\Local\Temp\scp16972\domains\dev.onter.site\public_html\ping\index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>How to Integrate Google “No CAPTCHA reCAPTCHA” on Your Website</title>
  </head>
  <body>
    <form action="" method="post">
      <label for="name">Name:</label>
      <input name="name" required><br />
      <label for="email">Email:</label>
      <input name="email" type="email" required><br />
      <div class="g-recaptcha" data-sitekey="6LfwmMgaAAAAANFNTFnb2XGDwNt5sQ-iGCGoMMR2"></div>
      <input type="submit" value="Submit" />
    </form>
    <!--js-->
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <?php 
      require_once "recaptchalib.php";
      // your secret key
      $secret = "6LfwmMgaAAAAAHMUD3fTIUNJxVAaLPoyZ9FH1HG1";
      // empty response
      $response = null;
      // check secret key
      $reCaptcha = new ReCaptcha($secret);
      // if submitted check response
      if ($_POST["g-recaptcha-response"]) {
          $response = $reCaptcha->verifyResponse($_SERVER["REMOTE_ADDR"],$_POST["g-recaptcha-response"]
        );
      }
      if ($response != null && $response->success) {
        echo "Hi " . $_POST["name"] . " (" . $_POST["email"] . "), thanks for submitting the form!";
      } else {
        echo "Haizzz";
      }
    ?>
  </body>
</html>

C:\Users\Administrator\AppData\Local\Temp\scp08146\domains\dev.onter.site\public_html\ping\recaptchalib.php

<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *    - Documentation and latest version
 *          https://developers.google.com/recaptcha/docs/php
 *    - Get a reCAPTCHA API Key
 *          https://www.google.com/recaptcha/admin/create
 *    - Discussion group
 *          http://groups.google.com/group/recaptcha
 *
 * @copyright Copyright (c) 2014, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
/**
 * A ReCaptchaResponse is returned from checkAnswer().
 */
class ReCaptchaResponse {
  public $success;
  public $errorCodes;
}
class ReCaptcha {
  private static $_signupUrl     = "https://www.google.com/recaptcha/admin";
  private static $_siteVerifyUrl =
    "https://www.google.com/recaptcha/api/siteverify?";
  private $_secret;
  private static $_version = "php_1.0";
  /**
   * Constructor.
   *
   * @param string $secret shared secret between site and ReCAPTCHA server.
   */
  function ReCaptcha($secret) {
    if ($secret == null || $secret == "") {
      die("To use reCAPTCHA you must get an API key from <a href='"
        . self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");
    }
    $this->_secret = $secret;
  }
  /**
   * Encodes the given data into a query string format.
   *
   * @param array $data array of string elements to be encoded.
   *
   * @return string - encoded request.
   */
  private function _encodeQS($data) {
    $req = "";
    foreach ($data as $key => $value) {
      $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
    }
    // Cut the last '&'
    $req = substr($req, 0, strlen($req) - 1);
    return $req;
  }
  /**
   * Submits an HTTP GET to a reCAPTCHA server.
   *
   * @param string $path url path to recaptcha server.
   * @param array  $data array of parameters to be sent.
   *
   * @return array response
   */
  private function _submitHTTPGet($path, $data) {
    $req      = $this->_encodeQS($data);
    $response = file_get_contents($path . $req);
    return $response;
  }
  /**
   * Calls the reCAPTCHA siteverify API to verify whether the user passes
   * CAPTCHA test.
   *
   * @param string $remoteIp   IP address of end user.
   * @param string $response   response string from recaptcha verification.
   *
   * @return ReCaptchaResponse
   */
  public function verifyResponse($remoteIp, $response) {
    // Discard empty solution submissions
    if ($response == null || strlen($response) == 0) {
      $recaptchaResponse             = new ReCaptchaResponse();
      $recaptchaResponse->success    = false;
      $recaptchaResponse->errorCodes = 'missing-input';
      return $recaptchaResponse;
    }
    $getResponse = $this->_submitHttpGet(
      self::$_siteVerifyUrl,
      array(
        'secret'   => $this->_secret,
        'remoteip' => $remoteIp,
        'v'        => self::$_version,
        'response' => $response,
      )
    );
    $answers           = json_decode($getResponse, true);
    $recaptchaResponse = new ReCaptchaResponse();
    if (trim($answers['success']) == true) {
      $recaptchaResponse->success = true;
    } else {
      $recaptchaResponse->success    = false;
      $recaptchaResponse->errorCodes = $answers[error - codes];
    }
    return $recaptchaResponse;
  }
}
?>

Bạn có thể nhìn thấy ví dụ thực tế của nó trên web, ví dụ như trên trang submit của @materialup.

Lấy No CAPTCHA reCAPTCHA

Chúng ta hãy đi thẳng vào vấn đề và bắt đầu với No CAPTCHA.

Bước 1

Bước 2

Bước 3

Bên dưới các khoá bạn sẽ thấy một số đoạn để bao gồm reCAPTCHA trên trang web của bạn. Đầu tiên đó là JavaScript:

Bạn cũng có thể định nghĩa một trong 40 ngôn ngữ được hỗ trợ mà bạn đang sử dụng bằng cách thêm một tham số vào chuỗi. Ở đây chúng ta đang thêm es, nó sẽ cung cấp cho chúng ta một reCAPTCHA ngôn ngữ Tây Ban Nha:

Đặt thẻ script này vào cuối trang (hoặc ngay bên dưới form nơi reCAPTCHA sẽ xuất hiện, tùy thuộc vào cách bạn ưu tiên tải nội dung của bạn).Advertisement

Bước 4

Tiếp theo là phần mẫu cái mà bạn sẽ cần phải thêm vào markup của form bất cứ nơi nào bạn muốn reCAPTCHA xuất hiện:

1

<div class="g-recaptcha" data-sitekey="6LcePAATAAAAAGPRWgx90814DTjgt5sXnNbV5WaW"></div>

Lưu ý: thuộc tính data-sitekey sẽ giữ giá trị của khoá của bạn, không phải ví dụ mẫu này.

Để biết thêm thông tin chi tiết về cấu hình reCAPTCHA của bạn hãy tìm hiểu tại developers.google.com.

Kết hợp lại với nhau

Bây giờ chúng ta đã có các thành phần ban đầu, đến lúc để đưa chúng vào môi trường làm việc.

Bước 1

Chúng ta hãy đặt thẻ script và phần mẫu của chúng ta vào một form đơn giản:

010203040506070809101112131415161718192021222324252627

<!DOCTYPE html><html lang="en"> <head> <title>How to Integrate Google “No CAPTCHA reCAPTCHA” on Your Website</title> </head> <body> <form action="" method="post"> <label for="name">Name:</label> <input name="name" required><br /> <label for="email">Email:</label> <input name="email" type="email" required><br /> <div class="g-recaptcha" data-sitekey="6LcePAATAAAAAGPRWgx90814DTjgt5sXnNbV5WaW"></div> <input type="submit" value="Submit" /> </form> <!--js--> <script src='https://www.google.com/recaptcha/api.js'></script> </body></html>

Để minh hoạ thử nghiệm reCAPTCHA đó đã vượt qua, chúng ta sẽ cần chạy một số kiểm tra bên phía máy chủ. Trong trường hợp này, chúng ta sẽ làm điều đó với PHP, do đó, hãy lưu tập tin này trong một dự án mới thành index.php.Advertisement

Bước 2

Bạn sẽ thấy rằng phương thức của form là post, vì vậy khi chúng ta submit dữ liệu form sẽ được trả về cho trang này trong một mảng các biến. Chúng ta có thể xuất các biến đó bằng cách lặp qua chúng, do đó hãy thêm các thứ sau đây vào đâu đó trong trang của bạn:

12345

<?php foreach ($_POST as $key => $value) { echo '<p><strong>' . $key.':</strong> '.$value.'</p>'; }?>

Bạn sẽ thấy giá trị trả về không chỉ nameemail, mà còn một giá trị g-recaptcha-response. Nếu bạn không hoàn thành bài kiểm tra CAPTCHA thì giá trị này sẽ được để trống, nhưng nếu bạn đã tích chọn hộp "I’m not a robot" bạn sẽ thấy một chuỗi rất lớn gồm các ký tự.

Đó là giá trị mà chúng ta cần gửi cho Google để nó có thể được xác nhận, vì vậy hãy làm điều đó tiếp theo.

Bước 3

Thật hạnh phúc, nhóm phát triển của Google đã làm được những công việc khó khăn cho chúng ta ở đây, vì vậy hãy tìm đến dự án ReCAPTCHA trên Github và lấy một bản sao của thư viện recaptchalib.php. Đặt nó trong thư mục gốc của dự án và sau đó tham chiếu đến nó ở đầu tập tin index.php của bạn:

123456

<?php // grab recaptcha libraryrequire_once "recaptchalib.php"; ?>

Bước 4

Thư viện này có chứa một tập hợp các hàm gửi g-rerecaptcha-response (cùng với khóa bí mật của chúng ta) đến Google thông qua một yêu cầu HTTP. Sau đó, chúng thu thập các phản hồi, kiểm tra xem CAPTCHA có thành công hay không. Để sử dụng cái này, đầu tiên chúng ta cần thiết lập một vài biến, trước thẻ đóng PHP:

12345678

// your secret key$secret = "6LcePAATAAAAABjXaTsy7gwcbnbaF5XgJKwjSNwT"; // empty response$response = null; // check secret key$reCaptcha = new ReCaptcha($secret);

ReCaptcha() kiểm tra xem khóa bí mật của chúng ta có hiện diện không. Nếu không nó tắt tiến trình và tư vấn cho chúng ta đi đến và nhận một cái. Sau đó chúng ta chạy các chi tiết của chúng ta thông qua những thứ sau đây:

1234567

// if submitted check responseif ($_POST["g-recaptcha-response"]) { $response = $reCaptcha->verifyResponse( $_SERVER["REMOTE_ADDR"], $_POST["g-recaptcha-response"] );}

Bước 5

Giả sử tất cả đều ổn với form được submit của chúng ta, biến $response sẽ báo cáo trở lại với "success" và chúng ta có thể tiếp tục xử lý dữ liệu form. Nó có thể trông như thế này: loại bỏ các bit nơi chúng ta lặp qua dữ liệu form, sau đó thêm kiểm tra sau đây bên trên form:

12345

<?php if ($response != null && $response->success) { echo "Hi " . $_POST["name"] . " (" . $_POST["email"] . "), thanks for submitting the form!"; } else {?>

Cuối cùng, thêm một thẻ đóng PHP sau form:

1

<?php } ?>

Điều này sẽ hiển thị form, trừ khi nó đã được submit thành công, trong trường hợp đó nó sẽ hiển thị một thông điệp cảm ơn nhỏ. Dưới đây là bản demo sau cùng.

Tóm tắt

Đây là một cài đặt PHP rất thô sơ và dễ dàng của No CAPTCHA reCAPTCHA. Nó mở ra cho những cải tiến, nhưng hy vọng nó sẽ giúp cho bạn nắm bắt được những điều cơ bản. Thư viện thuộc về nhóm phát triển của Google và tôi cũng gởi lời cảm ơn đến Matt Aussaguel đã chỉ cho tôi biết.

Các tài nguyên Hữu ích

Last updated