How to Add Google reCAPTCHA to a PHP Form with Example?
In this guide, we will integrate the Google reCAPTCHA in the PHP contact form. Utilizing this Google reCAPTCHA code, we can validate the human users and protect the form of submission from bots.
Integrating Google reCAPTCHA is recommended because It is an effective and efficient way of validating the user against bots. As we know already, the captcha is an idea particularly for validating real human users against bots.
![How to Add Google reCAPTCHA to a PHP Form with Example?](https://i.imgur.com/nOaMpYb.gif)
Here are the steps for integrating the Google reCAPTCHA:
- Get Google reCaptcha API Key.
- Create an HTML form.
- Integrate reCAPTCHA in a PHP form.
- Validate the response with Google reCAPTCHA.
Get Google reCaptcha API Key
To get the Google reCaptcha API key, you first have a Google account. And login into your Google account and visit this site https://www.google.com/recaptcha/admin.
Here you need to define the label name, the domain name in which you need to integrate Google reCaptcha.
![How to Add Google reCAPTCHA to a PHP Form with Example?](https://i.imgur.com/TkBhGOe.jpg)
Click on the “Save” button, and you will be redirected to a new page.
![How to Add Google reCAPTCHA to a PHP Form with Example?](https://i.imgur.com/UPUMagp.png)
Copy your reCAPTCHA Site Key and Secret Key. We will require these API keys in the following step.
Integrate Google reCAPTCHA in PHP Contact Form
To add the Google reCAPTCHA Widget in HTML Form, we need to put the reCAPTCHA JavaScript file on the web page. So, paste the following link before the body tag closes.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Next, add the g-recaptcha HTML tag inside the HTML Form, place it exactly where you might want to show the reCAPTHCA widget.
The g-recaptcha widget comes with the data-site key attribute. Here we need to paste the site key that we created in the previous step.
<div class="g-recaptcha" data-sitekey="Your_Site_Key"></div>
Here is the code for the Contact form:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Contact Form with Captcha</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container mt-5">
<h2>Implement Google reCAPTCHA in PHP Contact Form</h2>
<?php include('scripts/form.php'); ?>
<!-- Error messages -->
<?php if(!empty($response)) {?>
<div class="form-group col-12 text-center">
<div class="alert text-center <?php echo $response['status']; ?>">
<?php echo $response['message']; ?>
</div>
</div>
<?php }?>
<!-- Contact form -->
<form action="" name="contactForm" id="contactForm" method="post" enctype="multipart/form-data" novalidate>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" id="email">
</div>
<div class="form-group">
<label>Subject</label>
<input type="text" class="form-control" name="subject" id="subject">
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control" rows="4" name="message" id="message"></textarea>
</div>
<div class="form-group">
<!-- Google reCAPTCHA block -->
<div class="g-recaptcha" data-sitekey="6LfZ4AAVAAAAAFP6tyNYWgycDvXHIfjZg9shDZ05"></div>
</div>
<div class="form-group">
<input type="submit" name="send" value="Send" class="btn btn-dark btn-block">
</div>
</form>
</div>
<!-- Google reCaptcha -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</body>
</html>
Google reCAPTCHA Validation Before Form Submit in PHP
Form field validation ensures if the user has entered the necessary values or not. Google reCAPTCHA response is set off dependent on the PHP post request. The API call validates the token and returns the JSON response through the reCAPTCHA API and Secret key.
A user checks the reCAPTCHA checkbox to complete the reCaptcha challenge. If the reCAPTCHA response is successful form will be submitted, and the message will be displayed to the user.
<?php
if(isset($_POST["send"])) {
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
// Form validation
if(!empty($name) && !empty($email) && !empty($subject) && !empty($message)){
// reCAPTCHA validation
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
// Google secret API
$secretAPIkey = '6LfZ4AAVAAAAAF722GPGWyJ_lf1F2hMSWzPHmuYc';
// reCAPTCHA response verification
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$_POST['g-recaptcha-response']);
// Decode JSON data
$response = json_decode($verifyResponse);
if($response->success){
$toMail = "johndoe@gmail.com";
$header = "From: " . $name . "<". $email .">\r\n";
mail($toMail, $subject, $message, $header);
$response = array(
"status" => "alert-success",
"message" => "Your mail have been sent."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Robot verification failed, please try again."
);
}
} else{
$response = array(
"status" => "alert-danger",
"message" => "Plese check on the reCAPTCHA box."
);
}
} else{
$response = array(
"status" => "alert-danger",
"message" => "All the fields are required."
);
}
}
?>
So, this was the complete step by step process for utilizing Google reCaptcha with PHP and validate response using Ajax with PHP.