CAPTCHA (Completely Automated Public Turing Test To Tell Computers and Humans Apart) is used to protect unauthenticated form submission from automated script abuse. Captcha is usually used in the registration form, contact form and other publicly accessible forms. Captcha is considered one of the best methods to recognize whether the end-user is a human or a robot. Captcha can be in form of text-based, mathematical-based, image-based, 3D etc. There are many Captcha providers eg: hCaptcha ; Google reCaptcha; Captchas.net; Jcaptcha etc. This tutorial will show how to implement hCaptcha in CakePHP 4.
hCaptcha Registration
To use the hCaptcha services, the developer needs to register an account with hCaptcha. Click here to create hCaptcha account. Once you create the account and configure site, you will get the site key and secret key (check in your configuration).
Form View
In your form view, eg: add.php, add the following code to load the hCaptcha API JS.
<script src="https://js.hcaptcha.com/1/api.js" async defer></script>
Then, at the end of the form, add the following code to render the hCaptcha box. Replace the ‘YourSecretKey’ with your key.
<div class="h-captcha" data-sitekey="YourSecretKey"></div>
Controller
In the controller, add HTTP client to communicate with hCaptcha web service and remote API’s.
use Cake\Http\Client;
Then add the following code (add method). Change the ‘YourSecretKey’ with your key.
public function add()
{
$document = $this->Documents->newEmptyEntity();
if ($this->request->is('post')) {
$hcaptcha = $this->request->getData('h-captcha-response');
$httpClient = new Client();
$response = $httpClient->post('https://hcaptcha.com/siteverify', [
'secret' => 'YourSecretKey',
'response' => $hcaptcha,
]);
$hCaptchaResult = $response->getJson();
if ($hCaptchaResult['success']) {
$document = $this->Documents->patchEntity($document, $this->request->getData());
if ($this->Documents->save($document)) {
$this->Flash->success(__('The document has been saved.'));
return $this->redirect(['action' => 'index']);
}
} else {
$this->Flash->error(__('Captcha not fill'));
}
$this->Flash->error(__('Unable to save. Please, try again.'));
}
$this->set(compact('document'));
}
That’s all. Happy coding :)