Google reCAPTCHA integration with MVC PHP Framework CakePHP Version 2


Just follow the below steps to setup Google reCAPTCHA in your webpage very quickly.

Step 1:

Register for reCAPTCHA from google recaptcha website link, Click Here To Visit This Web Page

You will get Site key, Secret key Once submit, Preserve it.

Step 2:

Add the below script to your headers.


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

Step 3:

Add the below html code inside your form as your desire position to display Google reCAPTCHA. Replace your Google Site Key on Correct position given below.


  <div class="g-recaptcha" data-sitekey="#Replace This With Your Site Key From Google#"></div>

Step 4:

Final Code to check reCAPTCHA process complete successfully or not. paste the below code inside the controller method where the form will be posted.


  //reCaptcha Area start
  if (isset($this->request->data['g-recaptcha-response'])) {
    $captcha = $this->request->data['g-recaptcha-response'];
  }
  if (!$captcha) {
    $this->Session->setFlash(__('Please check the captcha form, try again.'), 'flash_error');
    $this->redirect(array('controller' => 'users', 'action' => 'register'));
  }
  $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=#Replace This With Your Secret Key From Google#&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
  if ($response . success == false) {
    $this->Session->setFlash(__('You are a spammer ! Get out'), 'flash_error');
    $this->redirect(array('controller' => 'users', 'action' => 'register'));
  } 
  //reCaptcha Area end

Advertisements