Getting fake inquiries, comments, and messages from users is really a headache. To get rid of spamming there are several libraries and tools which may solve this problem. But spammers usually find a way to bypass that spam prevention tool. Google also offers a spam filtering service called Google reCAPTCHA that minimizes the chances of getting spam. In this tutorial we will see how to integrate google reCAPTCHA v2 in PHP.
Steps in getting Google reCAPTCHA V2 Site Key and Secret Key:
- First of all go to https://www.google.com/recaptcha/admin/create
- Add label e.g: MySite
- Select reCAPTCHA v2
- Add domain name (e.g wdb24.com, example.com). For local host testing type localhost
- Accept term of service and Submit
- After submission you will receive SITE KEY and SECRET KEY
Steps in Google reCAPTCHA v2 Integration in PHP:
- Create a form and add
123<div class="g-recaptcha" data-sitekey="SITE_KEY"></div>
- Add
api.js
in footer like this - Once form will submit, get the user’s response token in
$_POST['g-recaptcha-response']
. - Verify token by sending it to
https://www.google.com/recaptcha/api/siteverify?secret=SECRET_KEY&response=G-RECAPTCHA-RESPONSE
. - Verify token returns JSON response with 4 keys.
- Success : true|false
- challenge_ts: timestamp,
- hostname: string,
- error-codes:[…]
- If response success returns true, User is legit otherwise user is fake.
Now let’s see a working example of google reCAPTCHA v2 in PHP. I will create a simple contact form with no validation and database insertion code. Here my aim is to show you the integration process.
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<div class="container"> <div class="row"> <div class="col-md-5 mt-2"> <h2>Contact Form</h2> <?php if(isset($error_msg)) { echo '<div class="alert alert-danger">'.$error_msg.'</div>'; } if(isset($success_msg)) { echo '<div class="alert alert-success">'.$success_msg.'</div>'; } ?> <form action="" method="POST"> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control form-control-sm" name="name" id="name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control form-control-sm" name="email" id="email"> </div> <div class="form-group"> <label for="subject">Subject</label> <input type="text" class="form-control form-control-sm" name="subject" id="subject"> </div> <div class="form-group"> <label for="message">Message</label> <textarea name="message" class="form-control " id="message" cols="20" rows="6"></textarea> </div> <div class="form-group"> <div class="g-recaptcha" data-sitekey="<?php echo $captchaSiteKey; ?>"></div> </div> <button type="submit" name="submit" class="btn btn-primary btn-flat">Submit</button> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script> <script src="https://www.google.com/recaptcha/api.js" async defer></script> |
In the above HTML I have used bootstrap for styling. $error_code
and $success_msg
will print error and success messages. $captchaSiteKey
variable holds the Site Key.
PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<?php $captchaSiteKey = 'XXXXXXXXXXXXXX'; $captchaSecretKey = 'XXXXXXXXXXXXXX'; function curlRequest($url) { $ch = curl_init(); $getUrl = $url; curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $getUrl); curl_setopt($ch, CURLOPT_TIMEOUT, 80); $response = curl_exec($ch); return $response; curl_close($ch); } if(isset($_POST['submit'],$_POST['g-recaptcha-response'])) { $createGoogleUrl = 'https://www.google.com/recaptcha/api/siteverify?secret='.$captchaSecretKey.'&response='.$_POST['g-recaptcha-response']; $verifyRecaptcha = curlRequest($createGoogleUrl); $decodeGoogleResponse = json_decode($verifyRecaptcha,true); if($decodeGoogleResponse['success'] == 1) { $name = htmlentities(trim($_POST['name'])) ; $email = htmlentities(trim($_POST['email'])); $subject = htmlentities(trim($_POST['subject'])); $message = htmlentities(trim($_POST['message'])); //save data in database $success_msg = 'Thank you'; } else { $error_msg = 'Invalid Captcha'; } } ?> |
In the above code $captchaSiteKey
and $captchaSecretKey
holds SITE KEY and SECRET KEY. curlRequest()
is a custom PHP function that takes url as a parameter and will return json response after using CURL. Next I have added isset
condition for submit and g-catpcha-response
. If both have values, then I will get g-catpcha-response
response and send to google. Once I will receive the JSON response in $verifyRecaptcha
. I will decode it and match $decodeGoogleResponse['success']
key. If $decodeGoogleResponse['success']
equals to 1 which means user is legit and I can add contact form data in database. Otherwise use is fake and I will print invalid captcha error.