phpmailer с recaptcha v3 не отправляет электронную почту - неопределенный индекс: g-recaptcha-response

У меня есть проблема с реализацией Google Captcha V3 с phpmailer. Когда я заполняю форму и нажимаю отправить. Произошла ошибка: Обратите внимание: неопределенный индекс: g-recaptcha-response в form.php в строке 6 Ошибка! Возникла проблема с капчей, вы обманули нас! ты робот! или вы просто не щелкнули по нему:) Ошибка говорит о том, что ошибка находится в строке 6 в form.php так: JS файл

<script src='https://www.google.com/recaptcha/api.js? 
render=6LemuWIUAAAAAATQOAxYz-30Uf8VbXery0I9J8ZA'></script>
<script>
grecaptcha.ready(function () {
  grecaptcha.execute('6LemuWIUAAAAAATQOAxYz-30Uf8VbXery0I9J8ZA', {
  action: 'form'
  })
});
</script>

PHP-файл:

<?php
date_default_timezone_set('Etc/UTC');
ini_set('display_errors',1);  error_reporting(E_ALL);
if(isset($_POST['submit'])){
   $userIP = $_SERVER["REMOTE_ADDR"];
  $recaptchaResponse = $_POST['g-recaptcha-response'];
  $secretKey = 'abc...';
  $request = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$recaptchaResponse}&remoteip={$userIP}");
  if(!strstr($request, "true")){
      echo '<div class="alert alert-danger" role="alert"><strong>Error!</strong>There was a problem with the Captcha, you lied to us! you are a robot! or you just didnt click it :)</div>';
  }
  else{
    if(isset($_POST['submit']))
    {
    $message=
    'name: '.$_POST['name'].'<br />
     email:  '.$_POST['email'].'<br />
     mess:   '.$_POST['message'].'
    ';
        require "class.phpmailer.php";
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = "ssl";
        $mail->Host = "abc...";
        $mail->Port = 465;
        $mail->Encoding = '7bit';
        $mail->SMTPDebug = 3;
        $mail->Username   = 'a@a.pl';
        $mail->Password   = 'abc';
        $mail->SetFrom($_POST['email'], $_POST['name']);
        $mail->AddReplyTo($_POST['email'], $_POST['name']);
        $mail->WordWrap = 50;
        $mail->MsgHTML($message);
        $mail->AddAddress('a@a.com');
        $result = $mail->Send();
        $message = $result ? '<div class="alert alert-success" role="alert"> 
  <strong>Success!</strong>Message Sent Successfully!</div>' : '<div 
  class="alert 
    alert-danger" role="alert"><strong>Error!</strong>There was a problem 
    delivering the message.</div>';  
         unset($mail);
     }
   }
}

HTML-файл:

    <form action="form.php" method="POST" class="contact__form g-recaptcha" 
    id="form" data-sitekey="6LdvpmIUAAAAABEO5KGWX1KsIJgPQnZyAJep4lkw">
   <div class="form__div">

     <label for="name">Name </label>
     <input type="text" name="name" id="name" class="input input__name" required/>

   </div>

   <div class="form__div">

     <label for="email">E-mail </label>
     <input type="email" name="email" id="email" class="input input__email " required/>

   </div>

   <div class="form__div">

     <label>Message </label>
     <textarea rows="5" aria-label="Write something" name="message" class="input input__mess" placeholder="Write..." minlength="10" maxlength="1000" required></textarea>

   </div>

 <button name="submit" type="submit" id="submit" class="form__button">Wyślij</button>

 </form>

2 ответа

Вы не передаете токен на запрос. Вы должны установить значение токена в форме. Вы можете сделать что-то вроде этого.

 grecaptcha.ready(function() {
    grecaptcha.execute("KEY_VALUE", {action: 'form'})
    .then(function(token) {
       localStorage.setItem('recaptcha_token', token)
       $('form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
     });
  });

Это не имеет ничего общего с PHPMailer - эта ошибка возникает до запуска любого кода PHPMailer.

Вы ищете значение в $_POST массив называется g-recaptcha-response, но этого не существует, отсюда и ошибка. У вас нет элемента ввода с таким именем, поэтому он отсутствует в $_POST, Возможно, что код Google добавляет его динамически из JS, но нет никаких доказательств того, что это происходит в том, что вы опубликовали. Я бы посоветовал вам больше читать документацию по recaptcha.

Здесь нет особых проблем, но вы используете очень старую версию PHPMailer и основали свой код на устаревшем примере.

Другие вопросы по тегам