Using new Google reCAPTCHA with PHP


Google has released the new reCAPTCHA. Using reCAPTCHA users can prove they are human without solving a CAPTCHA. They need just a single click to confirm they are not a robot. So, reCAPTCHA will protect your website from spam with better user experience. You can easily integrate Google reCAPTCHA in PHP script.

We have created a contact form with the new Google reCAPTCHA using PHP. Take a look the demo of Google reCAPTCHA in PHP from the Demo link. The reCAPTCHA integration process is given below.


Get reCAPTCHA API keys:

For adding reCAPTCHA to your site, you need to register your site and get reCAPTCHA API keys.
Register your site
Register your site at Google from here –


Get your Site Key.
Site key is used to display the reCAPTCHA widget.


Get your Secret Key.
Secret key helps authorizes communication between your site and the reCAPTCHA server.


HTML Code:

At first you need to include the reCAPTCHA API JavaScript library.

<script src="" async defer></script>

Before the Submit button we have placed the Google reCAPTCHA widget div. Modify the data-sitekey attribute value with your Site Key.

<form action="" method="POST">
    <input type="text" name="name" value="" />
    <input type="text" name="email" value="" />
    <textarea type="text" name="message"></textarea>
    <div class="g-recaptcha" data-sitekey="9LDDpf0eVtMZY6kdJnGhsYYY-5ksd-W"></div>
    <input type="submit" name="submit" value="SUBMIT">

PHP Code:

Into the PHP code you need to modify Google Secret Key.

if(isset($_POST['submit']) && !empty($_POST['submit'])):
$_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret '9LuDh9kyetYYYYdT0jsVckScsH8Ks3KA';
//get verify response data
$verifyResponse file_get_contents(''.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData json_decode($verifyResponse);
//contact form submission code
$name = !empty($_POST['name'])?$_POST['name']:'';
$email = !empty($_POST['email'])?$_POST['email']:'';
$message = !empty($_POST['message'])?$_POST['message']:'';
$to '[email protected]';
$subject 'New contact form have been submitted';
$htmlContent "
                <h1>Contact request details</h1>
                <p><b>Name: </b>"
                <p><b>Email: </b>"
                <p><b>Message: </b>"
// Always set content-type when sending HTML email
$headers "MIME-Version: 1.0" "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" "\r\n";
// More headers
$headers .= 'From:'.$name.' <'.$email.'>' "\r\n";
//send email
$succMsg 'Your contact request have submitted successfully.';
$errMsg 'Robot verification failed, please try again.';
$errMsg 'Please click on the reCAPTCHA box.';
$errMsg '';
$succMsg '';

Related Articles

Comments 0