Skip to main content

How to use Google reCaptcha with Cakephp 3.x

How to use Google reCaptcha with Cakephp






To use google reCaptcha with php you can read
In this tutorial we learn how to use google recaptcha with cakepphp 3.x we need two keys that provide by google .you can get your recaptcha keys from google developer account.

1.first we need to call google recaptcha js so open your projectFolder/src/template/layout/default.ctp or you can call it into your header.ctp

<?= $this->Html->script('https://www.google.com/recaptcha/api.js') ?>

2. Now we have to save keys into our project that we can access from anywhere so copy this code and paste it into YourProject/Config/bootstrap.php

 Configure::write('google_recatpcha_settings', array(
    'site_key'=>'SITEKEY',
    'secret_key'=>'SECRETKEY'
));


3.Now open your appConteoller (projectFolder/src/Controller/AppController)

Add these code into initialize function of appController

public function initialize()
    {
      $usecaptcha = 1;
      $this->set('usecaptcha',$usecaptcha); //we can on or off captcha on website by passing  0 or 1
    } 


AND ALSO ADD A NEW FUNCTION
public function verifyRecatpcha($aData)
        {
        if(!$aData)
        {
         return true;
        }
        if(isset($aData['g-recaptcha-response']))
        {
         $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;
         }
        }
        else
        {
         return false;
        }
        } 

4. Now create a controller(src/Controller/UsersController.php) and index.ctp(src/Template/Users/index.ctp) file of it. and create a form in index.ctp file and paste this code where you want to add google recaptcha

<?php if($usecaptcha==1) { ?>
              <div class="form-group">
              <div class="g-recaptcha" data-sitekey="<?php echo $publickeycaptcha; ?>"></div>
           </div>
        <?php } ?>


After adding these lines your register form will look like

<div class="col-sm-12 col-md-12 minheight">
  <div class="col-sm-3 col-md-3"></div>
  <div class="col-sm-6 col-md-6 content-box-large">
    <div class="users form">
      <?= $this->Flash->render() ?>
     
    <?= $this->Form->create() ?>
    <?= $this->element('error') ?>
        <fieldset>
            <legend><?= __('Register') ?></legend>

                <div class="form-group">
              <?= $this->Form->input('username', array('type' => 'text','class' => 'form-control','label' => 'Username','required'=>true)); ?>
            </div>
             <div class="form-group">
              <?= $this->Form->input('email', array('type' => 'text','class' => 'form-control','label' => 'Email','required'=>true)); ?>
             </div>
             <div class="form-group">
              <?= $this->Form->input('password', array('type' => 'password','class' => 'form-control','label' => 'Password','required'=>true)); ?>
            </div> 
              <div class="form-group">
              <?= $this->Form->input('confirm_password', array('type' => 'password','class' => 'form-control','label' => 'Confirm Password','required'=>true)); ?>
              </div>
            <div class="col-sm-12 paddingleftnone">
              <div class="col-sm-1 paddingleftnone paddingrightnone">
                <?= $this->Form->input('terms', ['type' => 'checkbox','class' => '','label'=>'']); ?>
              </div>
              <div class="col-sm-11 aligncenter paddingtopten" style="padding-top:13px;">I agree to the <a href="#">Terms of Use.</a>  </div>
          </div>   

       </fieldset>
        <?php if($usecaptcha==1) { ?>
              <div class="form-group">
              <div class="g-recaptcha" data-sitekey="<?php echo $publickeycaptcha; ?>"></div>
           </div>
        <?php } ?>
       <div class="form-group">
    <?= $this->Form->submit('Submit', array('div' => false,'class' => 'btn btn-success', 'title' => 'Create Account')); ?>
  </div>
       
    <?= $this->Form->end() ?>
    </div>
  </div>

</div>       



5.Now we have to check recaptcha that its valid or not in controller so open your UsersController and paste this code
 
public function register()
   {

 if ($this->request->is('post')) {

       if(usecaptcha==1)
        {
          if(!$this->verifyRecatpcha($this->request->data))
          {
           
              $this->Flash->error(__('Invalid Captcha, try again'),array('class' => 'alert alert-danger'));
              return  $this->redirect(array("controller" => "Users","action" => "register"));
          }
        }
    }
   }  
  


So thats all for how to use google reCaptcha with cakephp 3.x

Related Posts -
How to use google recaptcha
google reCaptcha with cakephp 3.x
How to use Google recaptcha in cakephp

Comments

Popular posts from this blog

Run and compile sass scss file to css using node

  Today we learn how to use scss and generate css using node  or Run and compile sass scss file to css using node   So please follow simple  steps :-   Today we will create a project that can read scss file and generates css with it  Note: Make sure you have installed node in your system. If you want to help to install node js based on your system then check our other tutorial or check node js official website. Now create a blank folder and open  terminal(linux) or cmd(windows) and navigate to your current project folder by using cd command Now run below command npm init after enter it will ask you some package info that you can fill according to you or just keep enter until it finished. The above command will generate package.json file Now  we will install npm module that will convert our scss to css Run below command: npm install node-sass So we have installed node-sass package . Now open package.json file in your...

How to retrieve Facebook Likes, share , comment Counts

function facebook_count($url){     // Query in FQL     $fql  = "SELECT share_count, like_count, comment_count ";     $fql .= " FROM link_stat WHERE url = '$url'";     $fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);     // Facebook Response is in JSON     $response = file_get_contents($fqlURL);     return json_decode($response); } $fb = facebook_count('https://www.facebook.com/BahutHoGyiPadhai'); // facebook share count echo $fb[0]->share_count;  echo "like"; // facebook like count echo $fb[0]->like_count ; echo "comment"; // facebook comment count echo $fb[0]->comment_count;  ?>

Solution-windows 'expo' is not recognized as an internal or external command

Solution for expo is not recognized as an internal or external command,operable program or batch file in Windows 10 Sometimes expo will not work globally mostly in windows 10, If you are facing same issue then follow the below Steps 1) Click on windows button and search for  " Environment variables"  and click on "Edit the system environment variables" 2) Now you will see a popup like below screen. Then you need to click on Environment Variables. (Please see highlight part in below image)     3)Then click on new button that i have highlighted in below image 4. Then a popup will open and you need to fill details like below mentioned Variable Name :Path Variable Value: %USERPROFILE%\AppData\Roaming\npm Here we are creating a new path variable and passing location of npm.   Now Click on OK and close all the terminal windows and open new CMD or terminal and type Expo . Great now you can access expo from any...