phpMailer和Google Captcha

时间:2017-12-11 23:48:02

标签: php phpmailer recaptcha

好的,在我的网站上我有一个联系表格,我用phpMailer发送电子邮件。它工作正常,但我一直收到垃圾邮件。所以我尝试将captcha合并到联系表单中。我有验证码设置的初始代码,但我不知道从哪里开始。我已经尝试将其余的代码放入验证码的声明中,但它不起作用。

任何帮助都会很棒

这是php代码:

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');

//Load composer's autoloader
require 'vendor/autoload.php';

if(isset($_POST['submit'])){
    $secret ='';
    $response = $_POST['g-captcha-response'];
    $rempteip = $_SERVER['REMOTE_ADDR'];

    $url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
    $result = json_decode($url,TRUE);

    if($result['success'] == 1) {

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

//validation
if(empty($name)){
    header("location: ../index.html?nouser");
    exit();
}

if(empty($phone)){
    header("location: ../index.html?nophone");
    exit();
}

if(empty($email)){
    header("location: ../index.html?noemail");
    exit();
}

if(empty($message)){
    header("location: ../index.html?nomessage");
    exit();
}


$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 0;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';                       // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = '';                 // SMTP username
    $mail->Password = '';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    // SENDER
    // this doesnt work with google use AddReplyTo
    // to be able to reply back to users email
    $mail->setFrom($email, sprintf('%s', $_POST['name']));

    //Recipients
    $mail->addAddress('darrells.webdesign@gmail.com', 'Darrell Pawson Jr');     // Add a recipient
    $mail->AddReplyTo($email);

    //wordwrap
    $mail->WordWrap = 50;

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = sprintf('New Message From %s', $_POST['name']);

    $mail->Body    = $strMessage = sprintf('%s<hr> Phone:  %s', $_POST['message'], $_POST['phone']);
    $mail->AltBody = strip_tags($body);

    $okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
    $errorMessage = 'There was an error while submitting the form. Please try again later';
    // Try to send the message
    if (!$mail->send()) { // Error
        // Set the error message
        $responseArray = [
            'type' => 'danger',
            'message' => sprintf('There was an error trying to send your message:  %s', $mail->ErrorInfo)
        ];
    } else { // Success
        // Set the success message
        $responseArray = [
            'type' => 'success',
            'message' => $okMessage
        ];
    }
}
finally{
    // Check for an XHR request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        // Send the header
        header('Content-Type: application/json');
        // Send the JSON response
        echo json_encode($responseArray);
    } else {
        // Send the message
        echo $responseArray['message'];
    }
}

以下是与之相关的js代码......(我不知道是否需要)

$(function () {
    'use strict';
    $('#form').validator();

    $('#form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
            var url = "./phpmailer/send.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data) {
                    var messageAlert = ' alert-' + data.type,
                        messageText = data.message,

                        alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    if (messageAlert && messageText) {
                        $('#form').find('.messages').html(alertBox);
                        $('#form')[0].reset();
                    }
                }
            });
            return false;
        }
    });
});

0 个答案:

没有答案