How to create a contact form using php and Google’s reCAPTCHA

You’ll have noticed captchas on many of the sites you use. When you try to send a contact message, or sign up to a new website, you’re asked to type the text you can see in a distorted picture, to check you really are a human being, not a robot.

captcha letter recognition test

But to keep up with letter recognition technology, Google has come up with a simplified test, called reCAPTCHA. In this test, you just tick a box and that is enough to prove you’re made of flesh and blood. If you make a mistake the first time, it may offer you another tickbox test to distinguish pictures from each other. It’s a pleasingly simple solution that’s easy to integrate into your contact form.

Re-captcha – it’s as easy as ticking a box.

Get started by collecting your reCAPTCHA site and secret keys from Google

Go to https://www.google.com/recaptcha/admin and sign in using your google account. Register the site, and get the two keys – site key and secret key – that you’ll be needing later for the construction of your contact form.

screenshot google reCAPTCHA keys

Now you’re ready to build your form.

Add the reCAPTCHA snippet inside the head tag of your contact page

head of contact.php

1

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

Build your form in html

body of contact.php.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?phpif(!empty($succMsg)):?>

<?phpecho$succMsg;?>

<?phpendif;?>

<?phpif(!empty($errMsg)):?>

<?phpecho$errMsg;?>

<?phpendif;?>

<strong>email</strong><br>

<form action=""method="POST">

<input type="text"value="<?phpecho!empty($contact_name)?$contact_name:'';?>"placeholder="your name"name="contact_name"required><?php//required attribute makes field required in html 5 browser, but may not work in safari?>