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

Convert website to android and ios application using react native expo webview

Convert website to android and ios application using react native expo webview If you want to check you can check on github by using below link also dont forget to give star ;) Source Code: https://github.com/shubham715/react-native-expo-webview-convert-website-to-app React native is the best choice to create multi platform mobile application , but sometimes we dont want to write a complete application because we already have a web application or a website and its complicated to manage both . So we have a solution for this problem. React native supports webView that makes easy to run any website url like an app natively. What is webview in react native? In React native, WebView helps to show web content in a native view. For this tutorial we will use EXPO. What is EXPO ? EXPO a set of tools to help you quickly start an app. Expo have many inbuilt components that helps to simplify the development and testing of React Native app. So please follow the below steps to c...

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...

Read files from folder using php

Read files from folder using PHP Today we learn how to read all files from a folder . we will learn to list all files and read all files . So please follow below steps:-   METHOD 1 1) List all files from folder If you want the list of all files in a folder then you can do by using below code //Get a list of file paths using the glob function. $allFilesList= glob('myfolder/*'); //Loop through the array that glob returned. foreach($allFilesList as $filename){ //Simply print them out onto the screen. echo $filename; echo '<br>'; } The above code will print list of all files like file1.jpg file2.png file3.gif file4.pdf   If you want to read only specific extension file like you just want to a list of all png files then you can do it by using below code. //Get a list of all files ending in .txt $fileList = glob('myfolder/*.png);   METHOD 2 Here is the second method. here we are using scandir() function to s...