· 7 years ago · Aug 19, 2018, 04:40 PM
1//The basic process of reCaptcha is as follows:
2
3/*
4
5-> Send gcaptcha to API
6-> Returns gcaptcha-response to validate validity of gcaptcha (via method POST)
7-> Server can then use selection with gcaptcha-response
8
9*/
10
11
12
13
14HTML (front end):
15
16<script src='https://www.google.com/recaptcha/api.js'></script>
17<div class="g-recaptcha" data-sitekey="xxxxxxxx"></div>
18
19
20PHP (back end):
21
22<?php
23
24require_once "recaptchalib.php";
25$secretKey = "xxxxxxxx";
26$ip = $_SERVER['REMOTE_ADDR'];
27$captcha;
28
29if(isset($_POST['g-recaptcha-response'])){ //checks if the returned g-raptcha-response isset (basically has the api successfully validated and returned the g-recaptcha request)
30 $captcha=$_POST['g-recaptcha-response'];
31 }
32 if(!$captcha){?> //if captcha variable has not been set above (basically captcha wasn't successfully completed, this doesn't mean that it was necessarily wrong just incomplete) you will be asked to complete the captcha again
33 <script language="javascript" type="text/javascript">
34 alert('Please complete the reCAPTCHA verification');
35 //consider redirection back to your form
36 </script>
37 <?php }
38
39
40 $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
41 $responseKeys = json_decode($response,true);
42 if(intval($responseKeys["success"]) == 1) { //finally check if the captcha response is successful
43 //do something
44 }
45 ?>