This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
This video will review the code needed to make Google's ReCaptcha work with your application. We'll take the first step in upgrading our application by moving the ReCaptcha credentials into environment variables.
Googles reCAPTCHA
Sign up for your own API keys
- Manage your reCAPTCHA API keys
- Enter your own label
- Choose reCAPTCHA v2
- Enter your domain (Dev and/or Production)
For workspaces, the domain is: treehouse-app.com - Accept the reCAPTCHA Terms of Service. 6 Finish by pushing the Register button
You will be given a "Site Key" and a "Secret Key". You will be able to go back and grab these credentials at any time.
Add the Site Key and Secret Key to your Environment Variables
FOR SECURITY PURPOSES, the only variable you need to secure is the secret key. The site key will be visible in the source code of your site.
SITE_KEY=your_site_key_value
SECRET_KEY=your_secret_key_value
Set up the form
- In the html header of the file which includes the form, you must link to the JavaScript for the reCAPTCHA
<script src='https://www.google.com/recaptcha/api.js' ></script>
- Between the opening and closing form tags, add the following div
<div class="g-recaptcha form-label-group" data-sitekey="<?php echo getenv('SITE_KEY'); ?>"></div>
Process the form
To check if the reCAPTCHA has be completed, send a request to the Google reCAPTCHA servers along with your Secret Key and the form response.
$captcha = json_decode(
file_get_contents(
'https://www.google.com/recaptcha/api/siteverify?secret='
.getenv('SECRET_KEY')
.'&response='.$_POST['g-recaptcha-response']
)
);
if ($captcha->success == false) {
//return and error and do not process the form
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up