user10746010
user10746010

Reputation:

How to validate that reCaptcha is checked

I'am creating a contact form that should send the mail if the Google reCaptcha v2 is checked. Now it echoes my text even if the reCaptcha is checked.

Ive tried moving around the reCaptcha snippet and tried to do a if(isset but seems not to work.

  $email = $_POST['email'];
  $subject = $_POST['subject'];
  $message = $_POST['message'];

  $errorEmpty = false;
  $errorEmail = false;
  $errorCaptcha = false;

  if(empty($name) || empty($email) || empty($subject) || empty($message)){
    echo "<span style='color: red;font-weight: bold;'>Fyll i alla fält!</span>";
    $errorEmpty = true;
  }
  if(empty($_POST['g-recaptcha-response'])){
    echo "<span style='color: red;font-weight:bold;'>reCaptchan är inte ifylld!</span>";
    $errorCaptcha = true;
  }
   elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
     echo "<span style='color: red;font-weight: bold;'>Du måste skriva in en giltig e-mail adress!</span>";
     $errorEmail = true;
   }
    else{
      echo "<span style='color: green;font-weight: bold;'>Ditt meddelande skickades, vi återkommer inom max 3 arbetsdagar!</span>";
    }

    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
      $secret = '';
      $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
      $responseData = json_decode($verifyResponse);
      if($responseData->success){
  $to = $email;
  $subject = $subject;
  $text = "Name: $name\n From: $name\n Message: $message";
  $headers = "From: $email";
  if($errorEmpty == false && $errorEmail == false && $errorCaptcha == false){
  mail($to,$subject,$text,$headers);
  }
 }
} // ReCaptcha 2

I want the mail() function to activate if the reCaptcha is checked, otherwise I want to echo a text to the user.

Upvotes: 0

Views: 339

Answers (2)

Galzor
Galzor

Reputation: 845

i took a look at your code and found some errors. i am pasting the corrected code below, try it and let me know if it solves your problem.

<?php
$error = false;
$output = '';

$name    = $_POST["name"];
$email   = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

if (empty($name) || empty($email) || empty($subject) || empty($message)) {
  $output = "<span style='color: red;font-weight: bold;'>Fyll i alla fält!</span>";
  $error = true;
}
if (empty($_POST['g-recaptcha-response'])) {
  $output = "<span style='color: red;font-weight:bold;'>reCaptchan är inte ifylld!</span>";
  $error = true;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $output =  "<span style='color: red;font-weight: bold;'>Du måste skriva in en giltig e-mail adress!</span>";
  $error = true;
}
if ($error) {
  echo $output;
} else {
  $secretKey = "YOUR-SECRET-KEY";
  $captcha=$_POST['g-recaptcha-response'];
  $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
    urlencode($secretKey) .  '&response=' . urlencode($captcha);
  $response = file_get_contents($url);
  $responseKeys = json_decode($response, true);
  if ($responseKeys["success"]) {

    // mail then
    $to = $email;
    $email_subject = $subject;
    $email_body = "Name: $name\n From: $name\n Message: $message";
    //Send the email!
    $mail_check = mail($to, $email_subject, $email_body);
    if ($mail_check) {
      echo "Mail Sent!";
    } else {
      echo 'Mail Failed';
    }
  } else {
    echo 'Response not Success';
  }
}
?>

Upvotes: 0

duckboy81
duckboy81

Reputation: 307

It's hard to tell where you're having an issue. Your current code will always echo some sort of message (albeit maybe you require a message to be displayed, success or failure).

If you are saying you aren't able to get if($responseData->success){ to correctly validate the checked box, I would recommend you take a look at the response data through the use of var_dump($responseData) and see if Google is trying to tell you something (bad secret key, domain name, etc).

As an alternate approach, you may look into using Google's PHP reCaptcha library as an easier method to handling this situation -- my code, for instance:

function validateRecaptcha(?String $gRecaptchaResponse) {

    /* API source from: https://github.com/google/recaptcha */

    $recaptcha = new ReCaptcha\ReCaptcha(***SECRET HERE***);

    $resp = $recaptcha->verify($gRecaptchaResponse, $_SERVER['REMOTE_ADDR']);

    return $resp->isSuccess();

}

PS: Be careful using empty to validate user input. If a user decided to submit a message with only 0 as the content, your if(...|| empty($message)){ check would fail.

See: https://www.php.net/manual/en/function.empty.php

Upvotes: 1

Related Questions