How to add google recaptcha on login form in cakephp | Codeexecute

How to add google recaptcha on login form in cakephp

(1)First register your domain and create site key and secret key here

(2)Open file app/Config/bootstrap.php and add following setting

<?php
	Configure::write('google_recatpcha_settings', array(
    'site_key'=>'your-domain-site-key',
    'secret_key'=>'your-domain-secret-key'
));
?>

(3)add following script in your layout file app/View/Layouts/default.ctp

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

(4)Open app/View/Users/login.ctp and add following html inside login form

<div class="g-recaptcha" data-sitekey="<?php echo Configure::read('google_recatpcha_settings.site_key'); ?>"></div>

(5)add following function in app/Controller/AppController.php

<?php
 public function verifyRecatpcha($aData)
 {
	if(!$aData)
	{
		return true;
	} 
	$recaptcha_secret = Configure::read('google_recatpcha_settings.secret_key');
	$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$aData['g-recaptcha-response'];	
	$response = json_decode(@file_get_contents($url));			
				
	if($response->success == true)
	{
		return true;
	}
	else
	{
		return false;
		
	}	
 }	 
?>

(6)Open file app/Controller/UsersController.php and add following code in login function after post values

<?php
if(!$this->verifyRecatpcha($this->request->data))
{
	$this->Session->setFlash(__('Captcha incorrect.'),'default',array('class' => ''));
	return $this->redirect('login');
}
?>