dongqu3623 2017-01-04 09:57
浏览 220
已采纳

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

I'm having trouble integrating the new Google reCaptcha into my existing form handling php script. Previously, it worked absolutely fine with the contact.html page redirecting the form to the contact.php email handler, but I kept getting a load of spam, hence the desire to use reCaptcha.

I use a separate php file to handle the emailing. The relevant contact.html code is as follows:

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

The existing code from the contact.php file is this:

<?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
=============================
";

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

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

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

This currently works fine, but when I try and integrate the reCaptcha validation into the php, the email doesn't generate and the success message in the php doesn't display on the webpage.

Any help in integrating the reCaptcha validation into the php file would be greatly appreciated!!

EDIT: the tag for the reCaptcha is in the of the html as required, and the widget displays and functions fine on the site. However, every example piece of code that I've tried to integrate into the existing php has not worked and the emails don't generate (hence why I've left it out in the php file above). Thanks in advance!

EDIT 2: I have revised the php script and attempted the clean it up following CoolCodeGuy's helpful comments. However, given my budget php skills, it now doesn't work. Please help!!

            <?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
=============================
";

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

    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条回答 默认 最新

  • dongliyi967823 2017-01-04 11:35
    关注

    I have updated the whole of your code to the way I would have done it (I run a social-networking site).

            <?php
    
        $sendTo = "me@me.com";
        $subject = "New message from contact form";
        $headers .= 'From: <example@example.com>' . "
    ";
    
        $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 
     Phone: $phone 
     Email: $email 
     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;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 swiftui @query 报错
  • ¥50 怎么解决刷卡或扫码后,点击软件输入框,win10屏幕键盘不会自动弹出的问题
  • ¥15 如何使用arcgispro的训练深度模型,发现water和nowater精度为0?(相关搜索:深度学习)
  • ¥20 matlab作业不太懂呀有问题能给个代码吗
  • ¥15 自制电路图为何无法驱动ESP01S?
  • ¥15 前端加access数据库
  • ¥15 ARCGIS 多值提取到点 ERROR 999999
  • ¥15 mysql异常断电, [MY-011971] [InnoDB]
  • ¥15 uni.onBluetoothDeviceFound熄屏不运行
  • ¥15 求PHDA糖尿病并发症数据集,有偿