将reCaptcha集成到现有contact.php中

将reCaptcha集成到现有contact.php中,php,recaptcha,Php,Recaptcha,我在将新的GoogleReCAPTCHA集成到现有的表单处理php脚本中时遇到了问题。以前,它在contact.html页面将表单重定向到contact.php电子邮件处理程序时工作得非常好,但我不断收到大量垃圾邮件,因此希望使用reCaptcha 我使用一个单独的php文件来处理电子邮件。相关contact.html代码如下: <form id="contact-form" method="post" action="contact.php" role="form"> <d

我在将新的GoogleReCAPTCHA集成到现有的表单处理php脚本中时遇到了问题。以前,它在contact.html页面将表单重定向到contact.php电子邮件处理程序时工作得非常好,但我不断收到大量垃圾邮件,因此希望使用reCaptcha

我使用一个单独的php文件来处理电子邮件。相关contact.html代码如下:

<form id="contact-form" method="post" action="contact.php" role="form">

<div class="messages"></div>
<div class="controls">

    <div class="row">
        <div class="col-md-7">
            <div class="form-group">
                <label for="form_name">Name *</label>
                <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required">
                <div class="help-block with-errors"></div>
            </div>
             <div class="form-group">
                <label for="form_email">Email *</label>
                <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="A valid email is required">
                <div class="help-block with-errors"></div>
        </div>
         <div class="form-group">
                <label for="form_phone">Telephone</label>
                <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter a contact telephone number (optional)">
                <div class="help-block with-errors"></div>
            </div>
         <div class="form-group">
                <label for="form_message">Message *</label>
                <textarea id="form_message" name="message" class="form-control" placeholder="Please enter your message *" rows="4" required="required" data-error="Please enter your message"></textarea>
                <div class="help-block with-errors"></div>
            </div>
        <p>
          <div class="g-recaptcha" data-sitekey="6LfsexAUAAAAAF_qKlK7De8kA7XM2MGrGKTyK60M"></div></p>

         <input type="submit" class="btn btn-success btn-send" value="Submit"></p>
         <br><p class="text-muted"><strong>*</strong> These fields are required.</p>
         </form>

名字*
电子邮件*
电话
信息*


*这些字段是必需的

contact.php文件中的现有代码如下:

<?php


$from= "example@example.com";
$sendTo = "me@me.com";
$subject = "New message from contact form";
$fields = array('name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please try again later';


try
{
$emailText = "You have new message from contact form\n=============================\n";

foreach ($_POST as $key => $value) {

    if (isset($fields[$key])) {
        $emailText .= "$fields[$key]: $value\n";
    }
}

mail($sendTo, $subject, $emailText, "From: " . $from);

$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);

header('Content-Type: application/json');

echo $encoded;
}
else {
echo $responseArray['message'];
}

将下面的代码合并到contact.php页面上

    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $privatekey = ""; //whatever your PRIVATE key is

    $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);

    $data = json_decode($response);

    if (isset($data->success) AND $data->success==true) {
   //verification succeeded
    $responseArray = $okMessage;
   }
   else
   {
   //verification failed
   $responseArray = $errorMessage;
   }

echo $responseArray;

为什么不在表单标签上使用javascript验证呢

<div class="g-recaptcha" id="rcaptcha"  data-sitekey="xxxx"></div>
     `      <form action="" method="post" onSubmit="return get_action()"> ` <span id="captcha"  style="color:red" /></span></div>

`       ` 


函数get_动作(表单)
{
var v=grecaptcha.getResponse();
如果(v.length==0)
{
document.getElementById('captcha').innerHTML=“您不能将captcha代码保留为空”;
返回false;
}
其他的
{
document.getElementById('captcha').innerHTML=“captcha已完成”;
返回true;
}
}

我已经按照我的方式更新了你的全部代码(我运行一个社交网站)


先生,您是明星,谢谢。电子邮件现在可以正常生成,但我无法让成功/失败消息正常工作。我已经在一次编辑中修改了php的原始评论(php不是我的强项,你可能知道)。请帮忙@JoeFlaherty看到了我的更新代码,可以在不使用数组的情况下集成到您的代码中(我个人认为太复杂了!)谢谢。我尝试过合并它,但它仍然不起作用-没有错误/成功消息或电子邮件。除了生成okMessage,我还希望它实际运行电子邮件脚本。我已将完整的修订脚本粘贴到原始评论中。谢谢。虽然很难相信,但我对JS的了解甚至比不上对php的了解。我正努力使事情尽可能简单!!非常感谢。电子邮件现在可以正常生成(假设您通过了reCaptcha)。但是,无论是在页面上还是在新页面上,仍不会生成成功/错误消息。我尝试了合并旧的成功代码($responseArray=array('type'=>'success','message'=>$okMessage);以及在php脚本的底部添加echo$responseArray['message'];但仍然没有成功…@JoeFlaherty对于'if(!empty($\u SERVER['HTTP\u X\u REQUESTED\u WITH'])和strotlower($\u SERVER)你打算做什么['HTTP_X_REQUESTED_WITH'])='xmlhttprequest'){$encoded=json_encode($responseArray);头('Content-Type:application/json'));echo$encoded;'要做的代码?什么是$encoded?@JoeFlaherty如果它不是真的那么重要,那么我建议将它删除,因为我认为它会停止else语句并停止echo代码。我发现了问题。它还合并了两个Javascript文件:contact.js和validator.js,它们是引导程序的一部分uite。我已经从contact.html文件中删除了它们,它现在可以正常工作,包括生成电子邮件和电子邮件。感谢您的帮助!
<div class="g-recaptcha" id="rcaptcha"  data-sitekey="xxxx"></div>
     `      <form action="" method="post" onSubmit="return get_action()"> ` <span id="captcha"  style="color:red" /></span></div>
   <script src='https://www.google.com/recaptcha/api.js'></script>
  <script>

  function get_action(form) 
    {
    var v = grecaptcha.getResponse();
if(v.length == 0)
{
    document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
    return false;
}
else
{
    document.getElementById('captcha').innerHTML="Captcha completed";
    return true; 
   }
   }
        <?php

    $sendTo = "me@me.com";
    $subject = "New message from contact form";
    $headers .= 'From: <example@example.com>' . "\r\n";

    $name = @$_POST['name'];
    $phone = @$_POST['phone'];
    $email = @$_POST['email'];
    $message = @$_POST['message'];

    $okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
    $errorMessage = 'There was an error while submitting the form. Please try again later';
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $privatekey = "xxxxxxxxx"; //whatever your PRIVATE key is
    $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
    $data = json_decode($response);

    $emailText = "Name: $name \n Phone: $phone \n Email: $email \n Message: $message";

if (isset($data->success) AND $data->success==true) {

    mail($sendTo, $subject, $emailText, $headers);
    $responseArray = $okMessage;
   }
   else
   {
   //verification failed
   $responseArray = $errorMessage;
   }

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
    }
    else {
    echo $responseArray;
    }