Add captcha server side valdation to contact.php script

This commit is contained in:
German Correa 2017-09-07 14:19:07 -03:00
parent 45b34dc24f
commit 8ee2160c6b

View File

@ -1,4 +1,22 @@
<?php
function verifyCaptcha(){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '6LeLxy4UAAAAABClplWLJUjZ1_nhX_-SI7CuNcm8',
'response' => $_POST["g-recaptcha-response"]
);
$options = array(
'http' => array (
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n',
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
return $captcha_success;
}
// process.php
$errors = array(); // array to hold validation errors
@ -16,6 +34,13 @@ $data = array(); // array to pass back data
if (empty($_POST['mensage']))
$errors['mensage'] = 'Mensaje is required.';
if(empty($_POST['g-recaptcha-response'])){
$errors['recaptcha'] = 'Debe validar el captcha';
}
else if(!verifyCaptcha()){
$errors['recaptcha'] = 'Error en la validación de ReCaptcha';
}
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
@ -48,4 +73,4 @@ $data = array(); // array to pass back data
// return all our data to an AJAX call
echo json_encode($data);
?>
?>