Verify reCAPTCHA token

Function PHP 1 revisions 169 2 years ago 2 years ago
 * Verify reCAPTCHA token given secret
 * @param  string $token  Token you got from front-end
 * @param  string $secret Secret you got after website registration
 * @return bool           Whether the verification passes
public static function verifyRecaptcha($token, $secret) {
	$url = 'https://www.google.com/recaptcha/api/siteverify';
	$data = [
		'secret'   => $secret,
		'response' => $token,

	$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($url, false, $context);
	return json_decode($result)->success;

This is a very simple function to verify the reCAPTCHA token you got after client-side verification.

Simply pass the token you got from your front-end as the first parameter, and the secret you got after you registered your website with Google as the second parameter. It will return false when the verification fails and true when the verification passes.