Last Updated on March 5, 2023 by Roshan Parihar
PHP contact form with Google reCaptcha is the most useful feature to protect your forms from spam bots. If you want to restrict spam submissions on your website, it can be the most effective solution for you.
Google reCaptcha can help you validate humans and robots when they submit the contact form. Integration with Google reCaptcha is the most recommended solution to stop spam and robot submissions.
If you are continuously getting spam emails from your contact forms, you must implement Google reCaptcha protection. Users just have to click the checkbox to confirm that they are humans and not robots.
In this post, you will learn how to generate the Google reCaptcha site key and secret key. You will also learn a step-by-step process on how to validate humans and robots with it on your PHP contact form. After the identity is confirmed that the user is human, the form will send emails.
So, let’s get started.
How to Create PHP Contact Form with Google reCaptcha (Step-by-step)
Here is the step-by-step process on how to create a contact form with Google Recaptcha in PHP:-
Step 1: Generate Google reCaptcha V2 API Keys
First of all, you need to create Site Key and Secret Key to make your Google reCaptcha work for your contact form.
Get the Site Key and Secret Key From Google reCaptcha V2
To get the keys from Google reCaptcha v2, you have to visit the Google reCaptcha admin panel and log in to your Google account.
After logging in, you will get the settings page where you have to make the following setting to get the Site key and Secret key:-
- Label: Add a name to identify your registration for Google Recaptcha. It can be the name of your domain to easily identify that you are creating this for the specified domain.
- reCaptcha type: Select version 2 (reCaptcha v2). The ‘I’m not a robot’ tickbox is pre-selected here.
- Domains: Add a domain name where you want to display the Google reCaptcha in forms. Press enter to make it selected.
- Owners: Your Google email address is already showing selected here.
- Accept reCaptcha Terms of Service: Click the checkbox that you agree to the Google API terms of use.
- Send alerts to owners: Click the checkbox if you want to get alerts on your submission.
When you complete the above fields, click the ‘Submit’ button to save your settings.
You will get the Google reCaptcha v2 Site key and Secret key as shown in the image below.
Let’s store the above site and secret in a separate PHP variable to use in your contact form.
1 2 3 4 5 |
<?php // Google reCAPTCHA API key configuration $site_key = '6LeIXMEkAAAAALIkGBMdB_N_CDYArmOWKbyskdG4'; $secret_key = '6LeIXMEkAAAAAJMOYLS6XMh2IfNOE2HFEXsYa5VE'; ?> |
Step 2: Create PHP Contact Form Design with Google reCaptcha
After creating and obtaining your Google reCaptcha keys, you have to create your contact form design. The below HTML code is the main structure of the contact form.
Starting from the top of the structure, it contains the Google reCaptcha API URL. After that, it contains the form with form fields like Name, Email, and Message. If you want to know the below form structure in detail, you can read our post on Simple HTML Contact Form.
The form also contains the Google reCaptcha <div>
with the site key just before the submit button. This is required to display the captcha inside the form.
HTML Code for PHP Contact Form with Google reCaptcha
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<script src="https://www.google.com/recaptcha/api.js" async defer></script> <div class="main-contact-form"> <!-- Place your Site key and Secret key here --> <form action="#" method="POST"> <label for="Name">Your Name</label> <input type="text" name="name" class="name" placeholder="Enter name" required> <label for="Email">Your Email</label> <input type="email" name="email" class="email" placeholder="Enter email" required> <label for="message">Message</label> <textarea name="message" class="message" placeholder="Enter your message" rows="5" required></textarea> <div class="g-recaptcha" data-sitekey="<?php echo $site_key; ?>"></div><br> <input name="submit" type="submit" value="Submit"> </form><br> <!-- Place PHP code here --> </div> |
Also, you have to place the previous step obtained site and secret keys in the indicated place below. The above form also indicated the place where you have to place the PHP code given in the last step.
CSS Code for PHP Contact Form with Google reCaptcha
The above HTML structure of the contact form is not enough to make a better design. To make it looks better to your audience. Add some CSS code before the closing <head> tag.
The below code contains CSS for all the form fields including the button element with error and success message CSS. However, it does not require adding CSS for the captcha code as it is standard and already designed beautifully by the Google team.
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 |
<style> input[type='text'],input[type='email'], textarea{ width: 100%; padding: 10px; border-radius: 3px; border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px; } input[type='text']:focus,input[type='email']:focus, textarea:focus{ border: 1px solid #5db6db; box-shadow: 0 0 10px #b9eaff; outline: none !important; } input[type='submit']{ background: rgb(39,160,210); color: #fff; border: none; padding: 10px 20px; cursor: pointer; } .main-contact-form{ max-width: 400px; margin: 0 auto; background: #e9e9e9; padding: 20px 45px 20px 25px; border-radius: 5px; } .error_message{ color: red; border:1px solid red; padding: 5px; } .success_message{ color: green; border:1px solid green; padding: 5px; } </style> |
After you add the above CSS to your contact form, it converts into a beautiful-looking contact form as shown in the image below. It also displays the Google reCaptcha to identify humans and robots.
Let’s add some PHP code to validate the form and Google reCaptcha to protect your form from spam bots.
Step 3: Send Email with Google reCaptcha Validation
The PHP code should validate the Google reCaptcha to stop spam bots. It should not allow users to submit the form without clicking the Captcha. The PHP code should also validate the email address to check if the format is correct or not.
The PHP code first gets the form data using the $_POST
global variable. After that, it validates the email address using the regex expression and the preg_match()
.
To validate the Google Recaptcha of the PHP contact form, you have to use the $_POST
global variable and get the Captcha field using g-recaptcha-response
. You have to check whether the captcha fields isset and are not empty to find whether users clicked it or not.
It only allows the further code to execute when getting the success validation response of Google Recaptcha. The below code is well commented to easily understand each part of the code. So, see the below PHP code to understand the use of the method.
Click the button given below to download the PHPMailer library whose link is given below. It is required to make the below code work to send emails as the below code uses the PHPMailer to send emails. It is the fastest and easiest way to send emails in 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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
<?php if(isset($_POST['submit'])){ // Get the submitted form data $email = $_POST['email']; $name = $_POST['name']; $message = $_POST['message']; //validation for email $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if (!preg_match($email_exp, $email)) { echo "<p class='error_message'>The email address you entered is not valid.</p>"; exit; } //Check if reCaptcha checked clicked or not if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){ // Verify the reCAPTCHA response $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']); // Decode json data $responseData = json_decode($verifyResponse); // If the reCAPTCHA response is valid if($responseData->success){ //If everything above is ok then move further to send emails using PHPMailer //Use PHPmailer require "phpmailer/PHPMailerAutoload.php"; $mail = new PHPMailer; //Mailbody to send in an email $mailbody = '<h4>Customer contact details:-</h4> <p><b>Name:</b> '.$name.'</p> <p><b>Email:</b> '.$email.'</p> <p><b>Message:</b> '.$message.'</p>'; //Sender email address $mail->isSMTP(); // Set mailer to use SMTP $mail->SMTPDebug = 0; //See errors, change it to 4 $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $sender; // SMTP username $mail->Password = 'yourgmailpassword';// Gmail SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom($email, $name); //$mail->addAddress('[email protected]'); //add more recipient (optional) $mail->addReplyTo($email, $name); //$mail->addCC('[email protected]'); //$mail->addBCC('[email protected]'); $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Contact Form Submitted by '.$name; $mail->Body = $mailbody; //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; //Email your contact form data using Gmail SMTP with PHPMailer if(!$mail->send()){ echo "Message could not be sent. Please try again."; echo 'Mailer Error: ' . $mail->ErrorInfo; }else{ echo "<p class='success_message'>Message has been sent successfully.</p>"; } }else{ echo '<p class="error_message">Robot verification failed, please try again.</p>'; } }else{ echo '<p class="error_message">Please check on the reCAPTCHA box.</p>'; } } ?> |
The above PHP code uses the PHPMailer of PHP to send emails with the user’s data entered into the contact form. If you want to use the mail function of PHP, you can read our post on PHP code for the contact form to send emails using mail()