【问题标题】:Contact form issue to handle Google reCaptcha response处理 Google reCaptcha 响应的联系表单问题
【发布时间】:2016-11-27 03:38:13
【问题描述】:

我正在尝试为我的联系表单实施 google reCaptcha。我已经阅读了一些关于 SA 的教程和帖子,但没有成功。

我的问题是,无论用户是否检查 reCaptcha,表单都会发送,就好像没有考虑 reCaptcha。

我使用了this post中描述的方法,下面是我的完整代码:

有什么问题?

非常感谢

表格

<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);


?>

【问题讨论】:

  • 你从不调用函数isValid,所以你不检查它。

标签: php ajax captcha contact-form recaptcha


【解决方案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 定义后需要调用。

【讨论】:

  • 谢谢!放“exit”合适吗?在其他之后?你能告诉我我的 PHP 文件的哪些部分应该代替 // 发送邮件吗? (当我查看 php 文件时,一切看起来都像变量,所以不确定哪个部分实际发送了电子邮件)。非常感谢
  • 这个发送它:$response = array(); if(!$mail-&gt;send()) { $response = array('message'=&gt;"Mailer Error: " . $mail-&gt;ErrorInfo, 'status'=&gt; 0); } else { $response = array('message'=&gt;"Message has been sent successfully", 'status'=&gt; 1); } 你可以退出,但你正在使用响应等待我编辑我的答案。
  • 其实好像有问题。即使 reCaptcha 在表单中得到正确验证,也不会发送消息:它显示来自 AJAX 文件的 #error_message。知道问题是什么吗?谢谢。
  • 你在html里面设置了正确的公钥,在php脚本里面设置了正确的私钥吗?
  • 糟糕,有错字!再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2021-09-15
相关资源
最近更新 更多