Проблема с контактной формой для обработки ответа Google reCaptcha

Я пытаюсь реализовать Google reCaptcha для своей контактной формы. Я прочитал несколько руководств и сообщений по SA, но безуспешно.

Моя проблема в том, что независимо от того, проверяет ли пользователь reCaptcha или нет, форма все равно отправляется, как если бы reCaptcha не принималось во внимание.

Я использовал метод, описанный в этом сообщении и посмотрите ниже мой полный код:

В чем проблема?

Большое спасибо

ФОРМА

<form action="sendmessage-test.php" class="well form-horizontal" id="contact_form" method="post" name="contact_form">

  fields etc.

  <button class="" name="submit" type="submit"> SEND</button>
  <div class="g-recaptcha" data-sitekey="mykey"></div>

         <!-- Success message -->
        <div class="alert alert-success" id="success_message" role="alert">
          Votre message a bien été envoyé. Merci!
        </div>
        <!-- error message -->
        <div class="alert alert-danger" id="error_message" role="alert">
          Le message n'a pas pu être envoyé. Veuillez nous contacter par téléphone. Merci.
        </div>

</form>

AJAX

$(document).ready(function() {

        $('#contact_form').bootstrapValidator({
            feedbackIcons: {
                valid: 'fa fa-check',
                invalid: 'fa fa-times',
                validating: 'fa fa-refresh'
            },
            fields: {
                first_name: {
                    validators: {
                            stringLength: {
                            min: 2,
                        },
                            notEmpty: {
                            message: 'Veuillez indiquer votre prénom'
                        }
                    }
                },
                 last_name: {
                    validators: {
                         stringLength: {
                            min: 2,
                        },
                        notEmpty: {
                            message: 'Veuillez indiquer votre nom'
                        }
                    }
                },
                email: {
                    validators: {
                        notEmpty: {
                            message: 'Veuillez indiquer votre adresse e-mail'
                        },
                        regexp: {
                        regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                        message: 'Veuillez indiquer une adresse e-mail valide'
                                }
                    }
                },
                message: {
                    validators: {
                          stringLength: {
                            min: 10,
                            max: 1000,
                            message:'Votre message doit faire plus de 10 caractères et moins de 1000.'
                        },
                        notEmpty: {
                            message: 'Veuillez indiquer votre message'
                        }
                        }
                    }
                }}).on('success.form.bv', function (e) {
                e.preventDefault();
              $('button[name="submit"]').hide();

              var bv = $(this).data('bootstrapValidator');
              // Use Ajax to submit form data
              $.post($(this).attr('action'), $(this).serialize(), function (result) {
                  if (result.status == 1) {
                      $('#success_message').slideDown({
                          opacity: "show"
                      }, "slow")
                      $('#contact_form').data('bootstrapValidator').resetForm();
                  } else {
                        $('#error_message').slideDown({
                          opacity: "show"
                      }, "slow")              }
              }, 'json');
          }
            );

    });

PHP

<?php

require 'PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

$email_vars = array(
    'message' => str_replace("\r\n", '<br />', $_POST['message']),
    'first_name' => $_POST['first_name'],
    'last_name' => $_POST['last_name'],
    'phone' => $_POST['phone'],
    'email' => $_POST['email'],
    'organisation' => $_POST['organisation'],
    'server' => $_SERVER['HTTP_REFERER'],
    'agent' => $_SERVER ['HTTP_USER_AGENT'],

);

// CAPTCHA


function isValid() 
{
    try {

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => 'mykey',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];

        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];

        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}



//Enable SMTP debugging. 
$mail->SMTPDebug = false;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.sendgrid.net";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "";                 
$mail->Password = "";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 587;                                   

$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name'];

//To be anti-spam compliant

/* $mail->From = $_POST['email']; */     
$mail->From = ('mail@');
$mail->addReplyTo($_POST['email']);



$mail->addAddress("@gmail.com");
//CC and BCC
$mail->addCC("");
$mail->addBCC("");

$mail->isHTML(true);

$mail->Subject = "Nouveau message ";

$body = file_get_contents('emailtemplate.phtml');

if(isset($email_vars)){
    foreach($email_vars as $k=>$v){
        $body = str_replace('{'.strtoupper($k).'}', $v, $body);
    }
}
$mail->MsgHTML($body);

/* $mail->Body =  $_POST['message']."<br><br>Depuis la page: ". str_replace("http://", "", $_SERVER['HTTP_REFERER']) . "<br>" . $_SERVER ['HTTP_USER_AGENT'] ; */


$response = array();
if(!$mail->send()) {
  $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
  $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}

/* send content type header */
header('Content-Type: application/json');

/* send response as json */
echo json_encode($response);


?>

person Greg    schedule 23.07.2016    source источник
comment
ну, вы никогда не вызываете функцию isValid, поэтому вы не проверяете ее.   -  person jmattheis    schedule 23.07.2016


Ответы (1)


Вам нужно вызвать функцию isValid, которую вы еще только определили.

$response = array();
if(isValid()) {
    // send mail
    if(!$mail->send()) {
        $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
    } else {
        $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
    }
} else {
    // handle error
    $response = array('message' => 'Captcha was not valid', 'status'=> 0);
}

Обратите внимание, что вам нужно вызвать isValid после того, как он был определен.

person jmattheis    schedule 23.07.2016
comment
Спасибо! Уместно ли поставить exit; после еще? Не могли бы вы сказать мне, какие части моего файла PHP я должен поместить вместо // отправки почты? (когда я смотрю на файл php, все выглядит как переменные, поэтому не уверен, какая часть на самом деле отправляет электронное письмо). Большое спасибо - person Greg; 23.07.2016
comment
это отправьте его: $response = array(); if(!$mail->send()) { $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0); } else { $response = array('message'=>"Message has been sent successfully", 'status'=> 1); } вы можете выйти, но вы используете ответ там, подождите, я редактирую свой ответ. - person jmattheis; 23.07.2016
comment
На самом деле вроде есть проблема. Сообщение не отправляется, даже если reCaptcha правильно проверен в форме: он показывает сообщение #error_message из файла AJAX. Есть идеи, в чем проблема? Спасибо. - person Greg; 23.07.2016
comment
вы установили правильный открытый ключ внутри html и правильный закрытый ключ внутри php скрипта? - person jmattheis; 23.07.2016
comment
Ой, да, была опечатка! В очередной раз благодарим за помощь! - person Greg; 23.07.2016
comment
Я снова :) Еще один вопрос, если можно: знаете ли вы, как я могу проверить в файле AJAX, что флажок recaptcha отмечен? (так же, как я проверяю, что другие поля были заполнены). Большое спасибо - person Greg; 23.07.2016
comment
Вы не можете, поскольку recaptcha необходимо проверить, что он проверен, вы можете добавить дополнительный запрос ajax, в котором вы только проверяете isValid(), а затем продолжаете использовать это значение. Когда вы застряли на каком-то этапе этого, вы можете задать новый вопрос (: - person jmattheis; 23.07.2016