Skip to main content

How to add google reCAPTCHA in form in PHP?

Add google reCAPTCHA in form in PHP





<html>
<head>
  <script src='https://www.google.com/recaptcha/api.js' async defer></script>
</head>
<body>
<?php 
if(isset($_POST['submit'])){
$captcha;

        if(isset($_POST['g-recaptcha-response'])){
          $captcha=$_POST['g-recaptcha-response'];
        }
        if(!$captcha){
          echo 'Please check the the captcha form.';
          exit;
        }
        $secretKey = "<!==== Secret key ====!>";
        $ip = $_SERVER['REMOTE_ADDR'];
        // post request to server
        $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
        $response = file_get_contents($url);
        $responseKeys = json_decode($response,true);
        // should return JSON with success as true
        if($responseKeys["success"]) {
                echo 'Thanks for posting';
echo $_POST['name'];
        } else {
                echo 'You are spammer ! Get the @$%K out';
        }

}
?>
<form action="" method="post">
<input type="text" name="name" placeholder="name" value="Hello World">
<div class="g-recaptcha" data-sitekey="<!==== Site key ====!>"></div>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

Comments

Popular posts from this blog

How to check date format in PHP?

Check date format in PHP function isCorrectDateFromat($date){     if(!empty($date)){         $dateString = $date; // Replace this with your date string         $format = "Y-m-d"; // Replace this with your expected date format         $dateTime = DateTime::createFromFormat($format, $dateString);         if ($dateTime === false) { /*             echo "The date is not in the correct format."; */         } else {             $errors = DateTime::getLastErrors();             if (empty($errors)) { /*                 echo "The date is in the correct format."; */                 return true;             } else { /*                 echo "...