Easily Add Google ReCaptcha v2 in PHP Mysql using Ajax Tutorial – Proper contact form example sending mail

Easily Add Google ReCaptcha v2 in PHP Mysql using Ajax Tutorial – Proper contact form example sending mail

Google Recaptcha example and integration in PHP

Get Website Site Key and Secret key

1. Get your Website site key and secret key which we will require forGoogle Recaptcha v2 integration. For that visit https://www.google.com/recaptcha/intro/v3.html and click on Admin Console.

Google Recptcha v2 using PHP

2. On next page click on Add site option after signing in with your Google account

Google Recptcha v2 using AJax

3. Next, fill website name in label, select ReCaptcha v2 and in domain enter your domain address as shown. Accept terms and conditions and click on Submit.

Get Site key and Secret Key for Recaptcha

4. Copy your site key and secret key in next step for adding reCaptcha v2 in PHP

Easily Add Google ReCaptcha v2 in PHP Mysql using Ajax Tutorial - Proper contact form example sending mail 1

Code to display recpatcha in index.html

Add the following script in head tag of index.html

<script src='https://www.google.com/recaptcha/api.js' async></script>

Add the following code in body where you want to display captcha usually in form

<form>
	<input type="text" id='name' name="name" placeholder="Name" class="form-control px-3" required><br>
	<input type="email" id='email' name="email" placeholder="Email" class="form-control px-3" required><br>
	<input type="number" pattern="[0-9]{12}" id='phone' name="phone" placeholder="Phone" class="form-control px-3" required><br>
	<div class="g-recaptcha mb-3" data-sitekey="YOUR SITE KEY"></div>
	<input onclick="myFunction()" type="button" value="Request Call Back" class="btn btn-primary">
</form>

Add the following js code check whether ReCaptcha has been checked by the user or not. If it is valid we send form data to sendform.php for further processing.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
		<script>
		function myFunction() {
		var response = grecaptcha.getResponse(); //This is response of captcha we will send for validating
		var name = document.getElementById("name").value;
		var email = document.getElementById("email").value;
		var phone = document.getElementById("phone").value;
		//Get form response and save in dataString
		var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&captcha=' + response;
//Check response length
		if (response.length == 0) {
		
		alert('Recaptcha is required');
		} //Check Mail valid or not
else if (!ValidateEmail(email)) {
		alert('Invalid Email');
		} else {
		// AJAX code to submit form.
		jQuery.ajax({
		type: "POST",
		url: "sendform.php",
		data: dataString,
		cache: false,
		success: function(html) {
		if (html == 'You are a spammer!') {
		alert(html);
		} else {
		alert(html);
		}
		}
		});
		}
		return false;
		}
//Function to check mail valid or not
		function ValidateEmail(mail) {
		var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return regex.test(mail);
		}


		</script>

Server-side validation for Google ReCaptcha v2 validation sendform.php

<?php
// Fetching Values From URL
if(isset($_POST['captcha'])){
$captcha = $_POST['captcha'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$decoded_response = json_decode($response, true);
if($decoded_response['success'] == true){

$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$from = $email;
    $to = "example@gmail.com";
    $subject = "New Mail ";
   
    // To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
 
// Create email headers
$headers .= 'From: '.$from."\r\n".
    'Reply-To: '.$from."\r\n" .
    'X-Mailer: PHP/' . phpversion();
     $message = '<html><body>';
$message .= "<h1 style='color:#f40;'>New Mail </h1>";
$message .= "<p style='color:#080;font-size:18px;'>Name : $name</p>";
$message .= "<p style='color:#080;font-size:18px;'>Email : $email</p>";
$message .= "<p style='color:#080;font-size:18px;'>Phone: $phone</p>";
$message .= '</body></html>';
    mail($to,$subject,$message, $headers);
    echo "Your email has been sent";
}
 else {
echo 'You are a spammer!';
}
}
?>

Note : Please replace YOUR SITE KEY in index.html and YOUR SECRET KEY in sendform.php with SITE KEY and SECRET KEY we generated at the start of tutorial.

Please share your reviews and ask any doubts or problems in the comments. And please also give your suggestions on more tutorials you want me to share.

Anmol Mathneja

I am Web Developer who loves sharing his work experiences with people. I provide services like Website Development, Website Designing and Digital Marketing. My areas of expertise include Core PHP, Codeigniter, Laravel, Wordpress, jQuery, Node JS, HTML, CSS.

This Post Has 3 Comments

  1. Lennart Ray

    Thanks for sharing this important information with us. After reading this article, i can also add ReCaptcha.

    1. techybro

      Thanks I am grateful you liked it. Always ready to share and help.

Leave a Reply