How to add google reCAPTCHA in php contact form
In this tutorial, we are going to integrate the Google reCAPTCHA in PHP. normally captcha is used for security purpose and only human users can pass through. computers or bots are not solving a captcha. so we will learn about captcha that how to integrate the Google reCAPTCHA in PHP.
First, we need to Google reCAPTCHA code library, site key and secret key. so first we go to Google reCAPTCHA panel and get site key and secret key.
After getting key, we will create a form using the bootstrap and pass the site key.
When the user fills the form data with resolves the reCAPTCHA code that time response token will be returned.
index.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 | <!DOCTYPE html> <html lang="en"> <head> <title>How to add google reCAPTCHA in php contact form</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <div class="container"> <form id="comment_form" action="check.php" method="post"> <div class="form-group"> <label for="name">Name:</label> <input type="text" class="form-control" id="name" name="name"> </div> <div class="form-group"> <label for="email">Email address:</label> <input type="email" class="form-control" id="email" name="email"> </div> <div class="form-group"> <div class="g-recaptcha" data-sitekey="here_enter_site_key"></div> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </body> </html> |
When the user submits the form that time sends the response token with form data. After checking the validation and return the final response.
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 | <?php $name = $_POST['name']; $email = $_POST['email']; if(!empty($name) && !empty($email)) { if(isset($_POST['g-recaptcha-response'])) $captcha=$_POST['g-recaptcha-response']; if(!$captcha){ echo '<h2>Please check the the captcha form.</h2>'; exit; } $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=here_enter_secret_key&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true); if($response['success'] == false) { echo '<h2>something went wrong please try again</h2>'; } else { echo '<h2>Thanks for posting comment.</h2>'; } } ?> |
If you like this article then You can see, comment and share this article demo