Menu


How to add google captcha in PHP form


1- Generate reCAPTCHA API Keys

Register your website at – Google reCAPTCHA Admin console.


2- Get the site Key and secret Key:

  1. Site Key – This key is used in the HTML code of the reCAPTCHA.
  2. Secret Key – This key helps to authorize communication between your site and the reCAPTCHA server.

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

index.php

<html>

<head>
  <meta charset="utf-8">
  <title>Google reCAPTCHA in PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>

  <div class="container mt-5">
    
    <h2>Google reCAPTCHA in PHP Contact Form</h2>

    <!-- Contact form -->
    <form action="varify_captcha.php" name="contactForm" method="post" enctype="multipart/form-data">
      <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" required>
      </div>
      <div class="form-group">
        <label>Phone</label>
        <input type="text" class="form-control" name="subject" required>
      </div>

      <div class="form-group">
        <!-- Google reCAPTCHA block -->
        <div class="g-recaptcha" data-sitekey="6LfZ4AAVAAAAAFP6tyNYWgycDvXHIfjZg9shDZ05"></div>
      </div>

      <div class="form-group">
        <input type="submit" name="send" value="Send" class="btn btn-primary btn-block">        
      </div>
    </form>
  </div>

  <!-- Google reCaptcha -->
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</body>

</html>

varify_captcha.php

<?php
 
  if(!empty($_POST['g-recaptcha-response']))
  {
        $secret = 'GOOGLE_CAPTACH_SECRET_KEY';
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);
        if($responseData->success)
            $message = "g-recaptcha varified successfully";
        else
            $message = "Some error in vrifying g-recaptcha";
       echo $message;
   }
?>