将reCaptcha集成到现有的contact.php中

时间:2017-01-04 09:57:52

标签: php recaptcha

我无法将新的Google reCaptcha集成到我现有的处理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'];
}

这目前工作正常,但是当我尝试将reCaptcha验证集成到php中时,电子邮件无法生成,并且php中的成功消息不会显示在网页上。

任何将reCaptcha验证集成到php文件中的帮助都将非常感谢!!

编辑:reCaptcha的标签根据需要位于html中,并且小部件在网站上显示和运行正常。但是,我尝试集成到现有php中的每个示例代码都没有工作,并且电子邮件不会生成(因此我将其留在上面的php文件中)。提前谢谢!

编辑2:我修改了php脚本并尝试按照CoolCodeGuy的有用评论进行清理。但是,鉴于我的预算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';
    $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);

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

    foreach ($_POST as $key => $value) {
    //verifcation passed
    if (isset($fields[$key])) {
        $emailText .= "$fields[$key]: $value\n";
    }
}

    mail($sendTo, $subject, $emailText, "From: " . $from);
    $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['message'];
    }

3 个答案:

答案 0 :(得分:0)

将以下代码合并到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;

答案 1 :(得分:0)

为什么不在表单标记上使用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>

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

答案 2 :(得分:0)

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

        <?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;
    }