CodeIgniter 4 Developer

PHP web developer home

Integrate Google ReCaptcha v3 in CodeIgniter 4

I created an extension to integrate Google ReCaptcha v3 in CodeIgniter 4.

Install via Composer

composer require denis303/codeigniter4-recaptcha:dev-master


In the file /.env you need to add your personal ReCaptcha keys (get them here).

# --------------------------------------------------------------------
# ReCaptcha
# --------------------------------------------------------------------
recaptcha.key = 'XXXXXXXX-XXXXXXXX'
recaptcha.secret = 'XXXXXXXX-XXXXXXXX'
recaptcha.scoreThreshold = 0.5

In the file /app/Config/Validation.php you need to add settings for validator:

public $ruleSets = [

Rendering ReCaptcha

Rendering of a hidden field ReCaptcha in the form:

helper(['form', 'form_recaptcha']);

echo form_open();

echo form_recaptcha3('test', ['id' => 'recaptcha_1']);

echo form_submit('submit', 'Submit');

echo form_close();

In the function form_recaptcha3, the first parameter you specify is the action for captcha, the second parameter being an attributes array captcha's hidden input. Please note that you cannot use hyphens in action.

Checking ReCaptcha

Checking ReCaptcha in a model:

public $validationRules = [
    'reCaptcha' => 'required|reCaptcha3[test]'

In the settings of the reCaptcha3 validator, the first parameter you specify is expectedAction, this parameter is obligatry.

public $validationRules = [
    'reCaptcha' => 'required|reCaptcha3[test,0.9]'

If necessary, you can override scoreThreshold the second validator parameter.

Custom Error

Setting custom ReCaptcha validation error in a model:

protected $validationMessages = [
    'reCaptcha' => [
        'reCaptcha3' => 'Captcha is not valid.'

That's all!

Advanced usage

You can get captcha validation errors:

$lastErrors = service('reCaptcha')->getLastErrors();

You can only get error codes, in the form they come in the service response:

$lastErrorCodes = service('reCaptcha')->getLastErrorCodes();

Get full response from the service:

$lastErrorCodes = service('reCaptcha')->getLastResponse();

Posted on 2020-03-16