Wednesday, 6 July 2022

Google Captcha Integration in Codeiginater 4

 Step 1 : 

    Signup to Google Recaptcha and get the public and private key.

Step 2 :

    Make a Model named CaptchaResponse in Model folder and add the given code below.

<?php

namespace App\Models;
use CodeIgniter\Model;
class CaptchaResponse extends Model
{           

       protected $bool ;
       protected $ErrorMessage ;       

}

Step 3 :

Make a function in which the controller, where the database record saves logic, is implemented.

public function ValidateCaptcha()
       {

            $secret ="Place your secrate code here";
             $recaptchaResponse = trim($this->request->getVar('g-recaptcha-response'));                    $credential = array(
            'secret' => $secret,
            'response' => $this->request->getVar('g-recaptcha-response')
             );

            $verify = curl_init();

          curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
          curl_setopt($verify, CURLOPT_POST, true);
          curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($credential));
          curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);

          $response = curl_exec($verify);
           $status= json_decode($response, true);

           if($status['success'])
           {

              return "1";

           }
          else
          {

             return "0";

          } 

    }

Step 4     

    Finally call the function created above in the method where database save code implements this function to check the captcha status, if it is validated then the function returns 1 otherwise 0. You implement your logic by checking return status 1. 

Step 5 :

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

<form   method="post" action="<?php echo site_url('/About/AddContactMsg'); ?>">

      <input type="text" name="Name" placeholder="Your Nme *" required>

      <input type="text" name="Phone" placeholder="Phone Number *" required>                                  

      <textarea name="Message"  placeholder="Type your message here.."></textarea>

      <div class="g-recaptcha" data-sitekey="Place your public code here">                                

      <input type="submit" name="submit" value="submit"   data-action='submit'  />                                                                                  

</form>

Next Topic

No comments:

Post a Comment