phalcon Validation Google reCaptcha custom validation component


Example

The class

use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\Message;

class RecaptchaValidator extends Validator implements ValidatorInterface
{
    public function validate(\Phalcon\Validation $validation, $attribute)
    {
        $value = $validation->getValue('g-recaptcha-response');
        $ip = $validation->request->getClientAddress();
        if (!$this->verify($value, $ip)) {
            $validation->appendMessage(new Message($this->getOption('message'), $attribute, 'Recaptcha'));
            return false;
        }
        return true;
    }
    
    protected function verify($value, $ip)
    {
        $params = [
            'secret' => 'YOUR_RECAPTCHA_SECRET_KEY',
            'response' => $value,
            'remoteip' => $ip
        ];
        $response = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?' . http_build_query($params)));
        return (bool) $response->success;
    }
}

Example usage in a Phalcon form:

$reCaptchaField->addValidator(new \RecaptchaValidator([
    'message' => 'Your reCaptcha error message'
]));