How to Verification re-captcha using HTML and PHP?

Verification re-captcha using HTML and PHP

How to Verification re-captcha using HTML and PHP?
How to Verification re-captcha using HTML and PHP?

To verify a reCAPTCHA using HTML and PHP, you'll need to follow these steps:

Step 1: Get the reCAPTCHA API keys

To use reCAPTCHA, you'll need to get API keys from the Google reCAPTCHA website. Go to https://www.google.com/recaptcha/admin and log in with your Google account. Then, select the "reCAPTCHA v2" option and fill in the necessary details. Once you've done this, you'll receive a site key and a secret key.

Step 2: Add the reCAPTCHA to your HTML form

Next, you need to add the reCAPTCHA to your HTML form. You can do this by adding the following code where you want the reCAPTCHA to appear:

Copy code

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

Make sure you replace "YOUR_SITE_KEY" with the site key you obtained in step 1.

Step 3: Verify the reCAPTCHA on the server-side

Finally, you need to verify the reCAPTCHA on the server-side using PHP. Here's some sample code that shows how to do this:

php

Copy code

$secret_key = "YOUR_SECRET_KEY";

$response = $_POST["g-recaptcha-response"];

$remote_ip = $_SERVER["REMOTE_ADDR"];


$url = "https://www.google.com/recaptcha/api/siteverify";

$data = array(

    "secret" => $secret_key,

    "response" => $response,

    "remoteip" => $remote_ip

);


$options = array(

    "http" => array(

        "header" => "Content-type: application/x-www-form-urlencoded\r\n",

        "method" => "POST",

        "content" => http_build_query($data)

    )

);


$context = stream_context_create($options);

$result = file_get_contents($url, false, $context);


if ($result === false) {

    // handle the error

} else {

    $result_json = json_decode($result, true);

    if ($result_json["success"] !== true) {

        // handle the verification failure

    } else {

        // the verification was successful, proceed with the form submission

    }

}

 

Make sure you replace "YOUR_SECRET_KEY" with the secret key you obtained in step 1. Also, note that this code assumes that the form is submitted using the POST method and that the reCAPTCHA response is stored in a variable named "g-recaptcha-response".

That's it! With these three steps, you can verify a reCAPTCHA using HTML and PHP.

Post a Comment

Post a Comment (0)

Previous Post Next Post