CakePHP 4 Integration of Google reCaptcha v2 Tutorial

Share this Article
Reading Time: 7 minutes
1,637 Views

Inside this article we will see the concept of CakePHP 4 Integration of Google reCaptcha v2 Tutorial. Google reCAPTCHA is a CAPTCHA system that enables web hosts to distinguish between human and automated access to websites.

Tutorial will help you to understand the integration of google recaptcha v2 in CakePHP 4. This will be step by step guide article.

Google reCaptcha that provide security against hackers and sticks or curl requests. It assures that a computer user is a human. It is the best and most used captcha system available where users are only required to click on a checkbox and in some cases select some similar images related to conman question.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Google reCaptcha Credentials

Open browser and hit this link, it will need to login via your google account. Please login to create google recaptcha credentials.

You need to do these,

  • Label name
  • Select reCaptcha version type
  • Domain to be linked

Click on Submit

Copy your Site Key and Secret Key from here.

Settings Constant Variables

Open paths.php file from /config folder and add these constants into it. We can also use .env file as well for this.

...

define('RECAPTCHAV2_SITEKEY', '6LeveR4fAAAAANh6IB68KD9G-WkHVS3C6xoSml2Z');

define('RECAPTCHAV2_SECRET', '6LeveR4fAAAAANre9WOIRBPXX2RTAqWMKpqGO7sB');

...

Create Controller

Open project into terminal and run this bake console command to create controller.

$ bin/cake bake controller Site --no-actions

It will create SiteController.php file inside /src/Controller folder.

Open SiteController.php write this complete code into it.

<?php

declare(strict_types=1);

namespace App\Controller;

class SiteController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel("Employees");
    }

    public function gCaptcha()
    {
        $employee = $this->Employees->newEmptyEntity();

        if ($this->request->is("post")) {
            // Form submit handler

            $postData = $this->request->getData();

            $recaptchaResponse = trim($postData('g-recaptcha-response'));

            // form data

            $secret = RECAPTCHAV2_SITEKEY;

            $credential = array(
                'secret' => $secret,
                'response' => $recaptchaResponse
            );

            $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']) {

                $this->Flash->success('Form has been successfully submitted');
            } else {

                $this->Flash->success('Please check your inputs');
            }
        }

        $this->set("employees", $employee);
    }
}

In the above code, you can see we have loaded Employees model. You can load your own model in place of it. This is only for demonstration.

Layout Template

Next,

Create a folder with name Site inside /templates folder. Inside Site folder, create a file with name g_captcha.php, folder path will be like this /templates/Sites.

Open g_captcha.php and write this code into it.

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>CakePHP 4 Integration of Google Recaptcha v2</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <style>
        .error {
            color: red;
        }
    </style>
</head>

<body>
    <div class="container" style="margin-top:30px;">

        <div class="row">
            <div class="col-md-9">
                <h3>User Form</h3>
                <?= $this->Flash->render() ?>
                <br />
                <?= $this->Form->create($employees, ["method" => "post"]) ?>
                <div class="form-group">
                    <label for="formGroupExampleInput">Name</label>
                    <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
                </div>
                <div class="form-group">
                    <label for="email">Email Id</label>
                    <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
                </div>
                <div class="form-group">
                    <label for="mobile_number">Mobile Number</label>
                    <input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number" maxlength="10">
                </div>
                <div class="g-recaptcha" data-sitekey="<?= RECAPTCHAV2_SITEKEY ?>"></div>
                <br />
                <div class="form-group">
                    <button type="submit" id="send_form" class="btn btn-success">Submit</button>
                </div>
                <?= $this->Form->end() ?>
            </div>
        </div>
    </div>
</body>

</html>

Disable CSRF Token

When we submit a cakephp form, it needs a CSRF token should be submitted with form submission request.

We are not interested to send CSRF token with form data. To disable it, Open Application.php from /src folder.

Remove these lines of code from middleware() method.

->add(new CsrfProtectionMiddleware([
    'httponly' => true,
]))

Add Route

Open routes.php from /config folder. Add this route into it.

//...

$routes->connect(
    '/captcha',
    ['controller' => 'Site', 'action' => 'gCaptcha']
);

//...

Application Testing

Back to terminal and run this command to start development server.

$ bin/cake server

URL: http://localhost:8765/captcha

Form submit with inputs

We hope this article helped you to learn CakePHP 4 Integration of Google reCaptcha v2 Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5