最新消息:

How to Integrate Google reCAPTCHA with PHP

网络 182浏览 0评论

在本教程中,我们将看到如何在PHP中使用Recaptcha或如何在PHP中使用Google reCaptcha代码。

Step 1. Register Your Site and Get API Key (Site Key and Secret key)

First, you need to register your website at Google reCaptcha admin console and get the site key and secret key.

Label: name of your site

reCatpcha type: Choose reCaptcha v2 >> Choose I’m not a robot Checkbox.

Domains: Mention the domain name of your website.

Register site to Google reCaptcha

Once submitted Google will provide you following two things:
1.Site Key
2.Secret Key

Register site to Google reCaptcha

Copy the Google reCaptcha site key and secret key for later use in the reCaptcha integration code.

HTML [Adding Google reCaptcha to Form]

First, include the reCAPTCHA JavaScript API library. Paste this snippet before the closing head tag on your HTML template:

<script src='https://www.google.com/recaptcha/api.js' async defer > 

Paste this snippet at the end of the form lable where you want the reCAPTCHA widget to appear and replace the below date-sitekey value with your own Site key.

<div class="g-recaptcha" data-sitekey="your_site_key"> 

For more details, you can see given below example.
Example:

<form method="POST">
   <input type="text" name="name" value="" /><br>
   <input type="text" name="email" value="" /><br>
   <textarea name="message"></textarea><br>
 
  <div class="g-recaptcha" data-sitekey="your_site_key"></div><br>
 
  <input type="submit" name="submit" value="SUBMIT">
</form>

Once you have done, refresh your web page and you will see reCaptcha widget added in form.

Step 3. PHP Code [Validate reCAPTCHA]

Replace the secret key with your own.

<?php
if(isset($_POST['submit'])){  

if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) { 
 
    $secretKey   = "your_site_key";
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP      = $_SERVER['REMOTE_ADDR'];
    $url         = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response    = file_get_contents($url);
    $response    = json_decode($response);
 
    if($response->success){
        echo "Verification success.";
    } else {
        echo "Verification failed";
    }

}
} ?> 

Once you have changed Secret Key with your own, you are done.
本文转载于:https://www.phpcluster.com/integrate-google-recaptcha-with-php/

您必须 登录 才能发表评论!