Skip to content

Instantly share code, notes, and snippets.

@HichemTab-tech
Last active July 31, 2023 22:30
Show Gist options
  • Save HichemTab-tech/3fe0b6839bf20e4a510c71ed16b97bc5 to your computer and use it in GitHub Desktop.
Save HichemTab-tech/3fe0b6839bf20e4a510c71ed16b97bc5 to your computer and use it in GitHub Desktop.
ReCaptchaHandler - A PHP class for Google ReCAPTCHA validation.

ReCaptchaHandler - A PHP class to handle Google ReCAPTCHA validation.

This PHP class provides a simple interface to validate Google ReCAPTCHA responses using the Google ReCAPTCHA API. It requires a valid server-side API key to work.

Usage:

  1. Include the 'ReCaptchaHandler.php' file in your PHP project.
  2. Get the ReCAPTCHA response token from the user (e.g., through a form submission).
  3. Use the 'ReCaptchaHandler::isResponseValid($response)' method to validate the token.
  4. The method returns 'true' if the token is valid, 'false' otherwise.

Note:

  • The 'ReCaptchaHandler' class uses the Google ReCAPTCHA API to validate tokens, so ensure your server has internet access.
  • To use the class, you need to obtain a valid server-side API key from the Google ReCAPTCHA website (https://www.google.com/recaptcha).

Author: @HichemTab-tech

<?php
require_once 'ReCaptchaHandler.php';
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the token from POST parameters
$token = $_POST['recaptcha_token'];
// Validate the token using ReCaptchaHandler class
$isValid = ReCaptchaHandler::isResponseValid($token);
// Output the result
if ($isValid) {
echo "Token is valid!";
} else {
echo "Token is invalid!";
}
}
/**
* ReCaptchaHandler - A PHP class to handle Google ReCAPTCHA validation.
*
* This class provides a simple interface to validate Google ReCAPTCHA responses
* using the Google ReCAPTCHA API. It requires a valid server-side API key to work.
*
* @link GitHub: [https://github.com/HichemTab-tech]
* @link GitHub Gist: [https://gist.github.com/HichemTab-tech]
*/
class ReCaptchaHandler
{
private const VALIDATION_URL = "https://www.google.com/recaptcha/api/siteverify";
/**
* Validate the ReCAPTCHA response with the Google ReCAPTCHA API.
*
* @param string $response The user's response to the ReCAPTCHA challenge.
* @return bool|null Returns true if the response is valid, false otherwise.
* @throws Exception Throws an exception if there is an error during validation.
*/
private static function validate($response): bool|null
{
//$apiServerKey = config('app.GoogleReCaptchaServerApi');
$apiServerKey = "YOUR_GOOGLE_RECAPTCHA_PRIVATE_API_KEY";
try {
$data = [
'secret' => $apiServerKey,
'response' => $response,
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = @file_get_contents(self::VALIDATION_URL, false, $context);
if (!$result) {
throw new Exception("Unable to connect to the Google ReCAPTCHA API.");
}
return json_decode($result)->success;
} catch (Exception $e) {
return null;
}
}
/**
* Check if the ReCAPTCHA response is valid.
*
* @param string $response The user's response to the ReCAPTCHA challenge.
* @return bool Returns true if the response is valid, false otherwise.
*/
public static function isResponseValid($response): bool
{
$res = self::validate($response);
if ($resObj = json_decode($res)) {
if (isset($resObj->success) && $resObj->success === true) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment