I remade reCAPTCHA PHP Client my own way
I shouldn’t have done this
Some days ago I checked the official reCAPTCHA PHP Client that Google provides, and I couldn’t feel that the package was pretty much forgotten in the sands of PHP 5.6. Okay, okay… it works for almost anybody, but I couldn’t stop thinking about how to make it a little better. Then I decided to make my own implementation for PHP 7.2 and using PSR standards.
Aaaaaand… I overdid it. I’m gonna enumerate the key advantages of this new implementation.
HTTP/2 and PSR-18
One of the things that is very broadly adopted is curl. The latest versions support HTTP/2, which is quicker, but the default package doesn’t uses it by default. You are left with obnoxious direct-to-metal implementations and errors that are difficult to check.
To cope with this problem, I opened the package to use any PSR-18 compliant HTTP clients, like the Symfony HTTP Client. The package only suggests it, it doesn’t install it. This uses HTTP/2 out of the box, and will fallback to HTTP/1.1 and streams on worst-case scenario.
Also, since only works with PSR-18, you can also have the benefit of capturing PSR-18 exceptions. Did reCAPTCHA servers when to oblivion? Did you forgot to open your network? Now you will know!
Easy to work with
Okay, we have in our application the g-recaptcha-response
token and we need to send it to reCAPTCHA servers. No problem, if we installed the suggested packages, we put our token and we are good to go:
$isValid = ReCaptcha::validate($secret, $token, $ip);
Yeah, one line to rule them all. Alternatively, you can use the make()
method to have more control:
$response = ReCaptcha::make($secret)
->threshold(0.7)
->action('login')
->verify($token, $ip);
Comes with an Exception
The good part of the new package is that you can verify or throw an FailedReCaptchaException
to stop the execution of your application. This means that our application can catch the exception and log it, which can be useful to check for a bot rush, or do anything else.
$response = ReCaptcha::make($secret)->verifyOrThrow($token, $ip);
Easy errors
You want to know why your response failed? No problem, just ask directly:
$response = ReCaptcha::make($secret)->verify($token, $ip)var_dump($response->error_codes);
// array(1) {
// [0] => string(10) "unknown-error"
// }
And if you catch the FailedReCaptchaException
, you will have access to the response using getResponse()
. Neat!
These are the major features I can think of. The library has 12% less code, but allows for lesser code redundancy in application or frameworks like Symfony, Drupal, Yii2 or Laravel.
If you want this package to be updated, you may want to give me your thumbs up in the PR I made not too long ago. I think a lot of integrators can benefit by this.