首页 > 解决方案 > 如何验证是否检查了 reCaptcha

问题描述

如果检查了 Google reCaptcha v2,我正在创建一个应该发送邮件的联系表单。现在,即使检查了 reCaptcha,它也会回显我的文本。

我试过移动 reCaptcha 片段并尝试做一个 if(isset 但似乎不起作用。

  $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

如果检查了 reCaptcha,我希望激活 mail() 函数,否则我想向用户回显文本。

标签: phprecaptcha

解决方案


很难说你在哪里有问题。您当前的代码将始终echo显示某种消息(尽管您可能需要显示消息,成功或失败)。

如果您说您无法if($responseData->success){正确验证复选框,我建议您通过使用查看响应数据var_dump($responseData),看看Google是否试图告诉您一些事情(错误的密钥、域名, ETC)。

作为一种替代方法,您可以考虑使用Google 的PHP reCaptcha 库作为处理这种情况的一种更简单的方法——例如我的代码:

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:小心使用empty验证用户输入。如果用户决定提交仅0作为内容的消息,您的if(...|| empty($message)){检查将失败。

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


推荐阅读