Search code examples
phprecaptchasanitization

Sanitise and validate $_POST['g-recaptcha-response'] in recaptcha


How do i sanitize and validate $_POST['g-recaptcha-response'] in recaptcha

https://github.com/google/recaptcha/blob/master/examples/example-captcha.php#L72

Looks like it gives a long string of alphanumeric characters, _ and - so will using strip_tags() to sanitize and check if it has only alphanumeric characters, _ and - to validate enough?


Solution

  • You can use strip_tags but this will not ensure that there are not other characters sent, like @, #, .... One solution would be to use preg_match to validate the string you receive:

    if (!preg_match('/^[\w-]*$/', $_POST['g-recaptcha-response'])) {
        echo 'invalid captcha';
    }