否则设置Google ReCaptcha并在字符串中输入错误

时间:2018-09-04 00:46:15

标签: php ajax

我正在尝试使用Google ReCaptcha验证给定的输入,并在必要时将错误消息发送到字符串中。目前,我有以下形式的问题块:

//Google ReCaptcha
if(isset($_POST['g-recaptcha-response'])) {
   // RECAPTCHA SETTINGS
   $captcha = $_POST['g-recaptcha-response'];
   $ip = $_SERVER['REMOTE_ADDR'];
   $key = 'SECRET_KEY';
   $url = 'https://www.google.com/recaptcha/api/siteverify';

   // RECAPTCH RESPONSE
   $recaptcha_response = file_get_contents($url.'?secret='.$key.'&response='.$captcha.'&remoteip='.$ip);
   $_POST = json_decode($recaptcha_response);

   if(isset($_POST->success) &&  $_POST->success === true) {
       // code goes here
   }
   else {
      die('Your account has been logged as a spammer, you cannot continue!');
   }
}

但是我的尝试是:

//Google ReCaptcha
if(isset($_POST['g-recaptcha-response'])) {
   // RECAPTCHA SETTINGS
   $captcha = $_POST['g-recaptcha-response'];
   $ip = $_SERVER['REMOTE_ADDR'];
   $key = 'SECRET_KEY';
   $url = 'https://www.google.com/recaptcha/api/siteverify';

   // RECAPTCH RESPONSE
   $recaptcha_response = file_get_contents($url.'?secret='.$key.'&response='.$captcha.'&remoteip='.$ip);
   $_POST = json_decode($recaptcha_response);

   else {
      $errors .= 'Captcha is Required.<br/>';
   }
}

那是不正确的,但想法仍然相同,我不确定如何完成此工作。

我还有其他字段,如果尚未填写,则进行评估,如果没有填写,则脚本将通过电子邮件发送内容。如果有错误,则错误消息将记录到$ errors字符串中,然后发送到JS脚本进行打印。

那么我该如何使用Google ReCaptcha完成相同的工作?

以下是所有需要它的人的完整脚本:

<?php
require_once 'config.php';
require 'vendor/autoload.php';

$response = [
    'status' => 'success',
    'message' => 'Mail sent successfully',
    'data' => []
];



//Checking is it ajax request
if (0 && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    //Invalid Ajax request
    http_response_code(403);
    $response = [
        'status' => 'error',
        'message' => 'Invalid request, please try again.',
        'data' => []
    ];
    responseHandler($response);
}

// $_POST = json_decode($_POST['data'], true); $errors = '';

//Email validation
if ( isset($_POST["userEmail"]) && !empty( $_POST["userEmail"] ) ) {
    $email = trim($_POST["userEmail"]);
    if ( filter_var($email, FILTER_VALIDATE_EMAIL) === false){
        $errors .= "$email is <strong>NOT</strong> a valid email address.<br/>";
    }
} else {
    $errors .= 'Please enter your email address.<br/>';
}
//Name Validation
if ( isset($_POST["userName"]) && !empty( $_POST["userName"] ) ) {
    $name = trim( $_POST["userName"] );
    if ( filter_var($name, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a valid name.<br/>';
    } elseif (!preg_match("/^[a-zA-Z ]*$/",$name)) {
        $errors .= 'Only letters and white space allowed for name...<br/>';
    }
} else {
    $errors .= 'Please enter your name.<br/>';
}

//Subject Validation
if ( isset($_POST["subject"]) && !empty( $_POST["subject"] ) ) {
    $subject = trim( $_POST["subject"] );
    if ( filter_var($subject, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a subject to send.<br/>';
    }
} else {
    $errors .= 'Please enter a subject to send.<br/>';
}

//Message Validation
if ( isset($_POST["message"]) && !empty( $_POST["message"] ) ) {
    $message = trim( $_POST["message"] );
    if ( filter_var($message, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a message to send.<br/>';
    }
} else {
    $errors .= 'Please enter a message to send.<br/>';
}

//Google ReCaptcha
if(isset($_POST['g-recaptcha-response'])) {
   // RECAPTCHA SETTINGS
   $captcha = $_POST['g-recaptcha-response'];
   $ip = $_SERVER['REMOTE_ADDR'];
   $key = '6LePAV4UAAAAAH_j3_F7LSlN1DShXlWNavBlK9Jk';
   $url = 'https://www.google.com/recaptcha/api/siteverify';

   // RECAPTCH RESPONSE
   $recaptcha_response = file_get_contents($url.'?secret='.$key.'&response='.$captcha.'&remoteip='.$ip);
   $_POST = json_decode($recaptcha_response);

   if(isset($_POST->success) &&  $_POST->success === true) {
       // code goes here
   }
   else {
      die('Your account has been logged as a spammer, you cannot continue!');
   }
}

if(!empty( $errors )) {
    http_response_code(400);
    $response = [
        'status' => 'error',
        'message' => $errors,
        'data' => []
    ];
    responseHandler($response);
}

//Filtering out newlines in the email subject
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
$contactContent = file_get_contents('email_templates/contact.html');;
$parameters = ['name' => $name, 'to_name' => TO_NAME, 'message' => $message ];

if(! send_mail( $email, $subject, $contactContent, $parameters ) ){
    //Email sent failed.
    http_response_code(500);
    $response = [
        'status' => 'error',
        'message' => 'Email service failing temporarily Or Maybe you are entered invalid E-mail, Please enter valid email and try again.',
        'data' => []
    ];
    responseHandler($response);
} else {
    //Email successfully sent
    http_response_code(200);
    responseHandler($response);
}

/**
 * responseHandler function
 * @param array $response request response
 */
function responseHandler($response)
{
    header('Content-type: application/json');
    echo json_encode($response);
    exit;
}

/**
 * send_mail function
 * @param  string $email             [[Description]]
 * @param  string $Subject           [[Description]]
 * @param  string $message           [[Description]]
 * @param  array [$parameters = []] [[Description]]
 * @return boolean  [[Description]]
 */

function send_mail($email, $Subject, $message, $parameters = []){
    ////Parse the message with given parameters
    if( !empty( $parameters ) )$message = parse($message, $parameters);



    $mail = new PHPMailer;
    //$mail->SMTPDebug = 3;                               // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = SMTP_HOST;  // Specify main and backup SMTP servers
    $mail->SMTPAuth = SMTP_AUTH;                               // Enable SMTP authentication
    $mail->Username = SMTP_USERNAME;
    $mail->Password = SMTP_PASSWORD;
    $mail->SMTPSecure = SMTP_SECURE;                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = SMTP_PORT;                                    // TCP port to connect to

    if( isset($parameters['name']) )
        $mail->setFrom($email, $parameters['name']);
    else
        $mail->setFrom($email);


    $mail->addAddress(TO_EMAIL);     // Add a recipient
    //$mail->addReplyTo($email, 'Smart Invoice V3 Promotion');
    $mail->addBCC(TO_EMAIL);

    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $Subject;

    $mail->Body = $message;
    $mail->AltBody = strip_tags($message);

    if(!$mail->send()) {//$mail->ErrorInfo;
        return false;
    }
    return true;
}


/**
 * parse function
 * @param  string $message    [[Description]]
 * @param  array $parameters [[Description]]
 * @return string [[Description]]
 */
function parse($message, $parameters) {
    foreach ($parameters as $key => $value) {
        $message = str_replace('{'.$key.'}', $value, $message);
    }
    return $message;
}

0 个答案:

没有答案