A useful PHP function to use Google reCAPTCHA



This one php function snippet can return true or false value after user submitted a form with Google reCAPTCHA in it.

function isCaptchaOkay($captchaPost) {
        $url = 'https://www.google.com/recaptcha/api/siteverify';
    	$data = array(
    		'secret' => 'YOURSECRETCODEHERE',
    		'response' => $captchaPost
    	);
    	$options = array(
    		'http' => array (
    			'method' => 'POST',
    			'content' => http_build_query($data),
    			'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                            "User-Agent:MyAgent/1.0\r\n",
    		)
    	);
    	$context  = stream_context_create($options);
    	$verify = file_get_contents($url, false, $context);
    	$captcha_success=json_decode($verify);
    	if ($captcha_success->success==false) {
    		return false;
    	} else if ($captcha_success->success==true) {
    		return true;
    	}
    }

Simply call isCaptchaOkay(); in an if statement to examine whether the user is allowed to go further or not (is he a human or not). For example:

if(isCaptchaOkay)
	echo "Welcome!";
else
	echo "You're not allowed to open this page.";
loading...

Leave a Reply

Your email address will not be published. Required fields are marked *