recaptcha in php

Google reCAPTCHA is a free service that protects your website from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart. To use reCAPTCHA in your PHP website, you’ll need to sign up for an API key pair. Here’s an example of how you can use reCAPTCHA in your PHP code:

Sign up for a reCAPTCHA API key pair at

Add the following code to the head section of your HTML file:

<script src=''></script>

Add the reCAPTCHA widget to your HTML form:

<form action="verify.php" method="post">
  <!-- Your form fields go here -->
  <div class="g-recaptcha" data-sitekey="your_site_key"></div>
  <input type="submit" value="Submit">

In the verify.php file, add the following code to verify the user’s response to the reCAPTCHA challenge:

$secret_key = 'your_secret_key';

// Check if the user has solved the reCAPTCHA challenge
$response = $_POST['g-recaptcha-response'];
$remote_ip = $_SERVER['REMOTE_ADDR'];

$url = '';
$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);
$result_json = json_decode($result);

if ($result_json->success) {
  // The user solved the reCAPTCHA challenge, process the form
  // ...
} else {
  // The user did not solve the reCAPTCHA challenge, display an error message
  echo "Please solve the reCAPTCHA challenge to submit the form.";

That’s it! With these steps, you should be able to use reCAPTCHA in your PHP website to protect your forms from spam and abuse.

Leave a Comment