recaptcha

repository·main·Indexed 25 days ago

https://github.com/google/recaptcha

Searchable repository documentation for Google Recaptcha from https://github.com/google/recaptcha.

Tokens
1.8K
Snippets
4
Records
11
Agent score
84%

What's inside google/recaptcha

  1. Implement a new RequestMethod

    main

    To add a new request method for communicating with the reCAPTCHA service, create a class that implements the ReCaptcha\RequestMethod interface. Following the project convention, name the class RequestMethod\_MethodType_Post (for example, RequestMethod\CurlPost). When implementing a new method, ensure it returns the following error codes where appropriate:

    • ReCaptcha::E_CONNECTION_FAILED
    • ReCaptcha::E_BAD_RESPONSE
  2. Verify reCAPTCHA responses

    main

    To verify a user's reCAPTCHA response on the server side, instantiate the \ReCaptcha\ReCaptcha class with your secret key and call the verify() method.

    verify() requires the reCAPTCHA response token (often found in $_POST or sent from JS) and the user's remote IP address. You can chain configuration methods to enforce specific validation rules before calling verify().

    <?php
    $recaptcha = new \ReCaptcha\ReCaptcha($secret);
    $resp = $recaptcha->setExpectedHostname('recaptcha-demo.appspot.com')
                      ->setExpectedAction('homepage')
                      ->setScoreThreshold(0.5)
                      ->verify($gRecaptchaResponse, $remoteIp);
    
    if ($resp->isSuccess()) {
        // Verified!
    } else {
        $errors = $resp->getErrorCodes();
    }
  3. Use the ReCaptcha class to verify responses

    main

    To verify a reCAPTCHA response, instantiate the ReCaptcha\ReCaptcha class with your secret key. You can optionally chain methods like setExpectedHostname() to apply additional validation rules. Call verify() passing the reCAPTCHA response and the user's remote IP address. The method returns a response object that can be checked for success using isSuccess() or for errors using getErrorCodes().

    <?php
    $recaptcha = new \ReCaptcha\ReCaptcha($secret);
    $resp = $recaptcha->setExpectedHostname('recaptcha-demo.appspot.com')
                      ->verify($gRecaptchaResponse, $remoteIp);
    if ($resp->isSuccess()) {
        // Verified!
    } else {
        $errors = $resp->getErrorCodes();
    }
  4. Install the reCAPTCHA PHP client library

    main

    You can install the library using Composer (recommended) or via direct download.

    Using Composer

    Run the following command in your project directory:

    composer require google/recaptcha "^1.5"

    Alternatively, add this to your composer.json:

    "require": {
        "google/recaptcha": "^1.5"
    }

    Direct Download

    1. Download the ZIP file from the repository.
    2. Extract it into your project.
    3. Require the provided autoloader script:
    require_once '/path/to/recaptcha/src/autoload.php';

    Note on PHP Versions: This library requires PHP 8 or higher. For earlier versions of PHP, you must use the 1.2 releases.

  5. Run reCAPTCHA library examples

    main

    You can run the included examples locally using the built-in PHP development server via Composer:

    composer run-script serve-examples

    Once running, the examples will be available at http://localhost:8080/.

  6. Configure ReCaptcha validation rules

    main

    The \ReCaptcha\ReCaptcha class provides several setter methods to enforce validation. These methods return the instance, allowing for method chaining.

    • setExpectedHostname($hostname): Ensures the hostname matches. Use this if you have disabled "Domain/Package Name Validation" for your credentials. To validate against multiple hostnames, call verify() and then check $resp->getHostname() against your allowed list.
    • setExpectedApkPackageName($apkPackageName): Used for verifying responses from Android apps (requires disabling "Domain/Package Name Validation").
    • setExpectedAction($action): Ensures the action matches (required for reCAPTCHA v3).
    • setScoreThreshold($threshold): Sets a score threshold for reCAPTCHA v3 responses.
    • setChallengeTimeout($timeoutSeconds): Sets a timeout between the user passing the challenge and the server processing it.
  7. Configure HTTP request methods

    main

    By default, the library attempts to use cURL (\ReCaptcha\RequestMethod\CurlPost). If cURL is unavailable, it falls back to file_get_contents() via \ReCaptcha\RequestMethod\Post.

    You can explicitly specify a request method by passing a RequestMethod instance to the ReCaptcha constructor.

    Available methods include:

    • \ReCaptcha\RequestMethod\CurlPost: Forces the use of cURL.
    • \ReCaptcha\RequestMethod\Post: Uses file_get_contents() and stream_context_create().
    • \ReCaptcha\RequestMethod\SocketPost: Uses a socket connection.
  8. Configure additional verification checks

    main

    The ReCaptcha client allows you to enforce additional validation rules during the verify() call using a fluent interface. These checks are performed locally after receiving the API response.

    • setExpectedHostname(string $hostname): Ensures the response hostname matches (e.g., www.google.com).
    • setExpectedApkPackageName(string $apkPackageName): Ensures the APK package name matches for mobile integrations.
    • setExpectedAction(string $action): Ensures the reCAPTCHA action matches the expected action for the current page.
    • setScoreThreshold(float $threshold): Ensures the reCAPTCHA score is greater than or equal to the provided float (between 0 and 1).
    • setChallengeTimeout(int $timeoutSeconds): Ensures the time elapsed since the challenge timestamp does not exceed the specified seconds.
  9. Initialize the ReCaptcha client

    main
    To use the reCAPTCHA service, instantiate the ReCaptcha eCaptcha class by providing your shared secret key. You can optionally provide a custom RequestMethod instance. If no method is provided, the library defaults to RequestMethod\CurlPost if the curl extension is available, otherwise it falls back to RequestMethod\Post.
  10. Reference reCAPTCHA error codes

    main

    The ReCaptcha class defines several constant error codes used when a verification fails or an error occurs during the process:

    ConstantValueDescription
    E_INVALID_JSONinvalid-jsonInvalid JSON received from the service
    E_CONNECTION_FAILEDconnection-failedCould not connect to the service
    E_BAD_RESPONSEbad-responseDid not receive a 200 from the service
    E_UNKNOWN_ERRORunknown-errorNot a success, but no error codes received
    E_MISSING_INPUT_RESPONSEmissing-input-responsereCAPTCHA response not provided
    E_HOSTNAME_MISMATCHhostname-mismatchExpected hostname did not match
    E_APK_PACKAGE_NAME_MISMATCHapk_package_name-mismatchExpected APK package name did not match
    E_ACTION_MISMATCHaction-mismatchExpected action did not match
    E_SCORE_THRESHOLD_NOT_METscore-threshold-not-metScore threshold not met
    E_CHALLENGE_TIMEOUTchallenge-timeoutChallenge timeout