Adding Google ReCaptcha


#1

I have a AJAX contact form and the error messages are printed right below the field. I want to add Google ReCaptcha to it but my attempt it isn’t working correctly, specifically, it does not appear to be checking if it was filled out or not and returning an error if necessary.

Can anyone look and see where am I making a mistake?

main (ajax.php):

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

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



//Checking is it ajax request
if (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);
}

if( !isset($_POST['data']) ) {
    http_response_code(400);
    $response = [
        'status' => 'error',
        'message' => 'Empty post data.',
        'data' => []
    ];
    responseHandler($response);
}
$data = json_decode($_POST['data'], true); $errors = '';

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

//Last Name Validation
if ( isset($data["lastName"]) && !empty( $data["lastName"] ) ) {
    $name = trim( $data["lastName"] );
    if ( filter_var($lastName, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a valid name.<br/>';
    } elseif (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
        $errors .= 'Only letters and white space allowed for last name...<br/>';
    }
} else {
    $errors .= 'Please enter your name.<br/>';
}

//Company Name Validation
if ( isset($data["companyName"]) && !empty( $data["companyName"] ) ) {
    $name = trim( $data["companyName"] );
    if ( filter_var($companyName, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a valid name.<br/>';
    } elseif (!preg_match("/^[a-zA-Z ]*$/",$companyName)) {
        $errors .= 'Only letters and white space allowed for company name...<br/>';
    }
} else {
    $errors .= 'Please enter your name.<br/>';
}

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

//City Name Validation
if ( isset($data["city"]) && !empty( $data["city"] ) ) {
    $name = trim( $data["city"] );
    if ( filter_var($city, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a valid city.<br/>';
    } elseif (!preg_match("/^[a-zA-Z ]*$/",$city)) {
        $errors .= 'Only letters and white space allowed for city name...<br/>';
    }
} else {
    $errors .= 'Please enter your city name.<br/>';
}


//Message Validation
if ( isset($data["message"]) && !empty( $data["message"] ) ) {
    $message = trim( $data["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 (empty($_POST['g-recaptcha-response']))
		$errors['recaptcha'] = 'Captcha is required.';


// return a response ===========================================================

// Check ReCaptcha Validation

if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
{
		$errors['recaptcha'] = 'Captcha is required.';
}


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

recaptcha.php:

<?php

function validateRecaptcha($secret, $clientResponse, $clientIp)
{
    $data = http_build_query([
        "secret_password"   => $secret,
        "response" => $clientResponse,
        "remoteip" => $clientIp,
    ]);

    $options = [
        "http" => [
            "header" =>
                "Content-Type: application/x-www-form-urlencoded\r\n".
                "Content-Length: ".strlen($data)."\r\n",
            "method"  => "POST",
            "content" => $data,
        ],
    ];

    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify",
        false,
        stream_context_create($options)
    );

    if($response === false)
    {
        return false;
    }
    else if(($arr = json_decode($response, true)) === null)
    {
        return false;
    }
    else
    {
        return $arr["success"];
    }
}

index.html:

<!doctype html>
<html>
<head>
	<title>Form Master</title>
	<script src='https://www.google.com/recaptcha/api.js'></script>
	<!-- Bootstrap -->
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<!--<link rel="stylesheet" href="css/super_bootstrap.min.css">-->
	<link rel="stylesheet" href="css/sweetalert/sweetalert.css">
	<link rel="stylesheet" href="css/style.css">
	<!-- Ripple CSS -->
	<!--

	<style type='text/css'>
	width:100%; @-webkit-keyframes uil-ripple{0%{width:0;height:0;opacity:0;margin:0}33%{width:44%;height:44%;margin:-22% 0 0 -22%;opacity:1}100%{width:88%;height:88%;margin:-44% 0 0 -44%;opacity:0}}@-ms-keyframes uil-ripple{0%,100%{opacity:0}0%{width:0;height:0;margin:0}33%{width:44%;height:44%;margin:-22% 0 0 -22%;opacity:1}100%{width:88%;height:88%;margin:-44% 0 0 -44%}}@-moz-keyframes uil-ripple{0%{width:0;height:0;opacity:0;margin:0}33%{width:44%;height:44%;margin:-22% 0 0 -22%;opacity:1}100%{width:88%;height:88%;margin:-44% 0 0 -44%;opacity:0}}@-webkit-keyframes uil-ripple{0%{width:0;height:0;opacity:0;margin:0}33%{width:44%;height:44%;margin:-22% 0 0 -22%;opacity:1}100%{width:88%;height:88%;margin:-44% 0 0 -44%;opacity:0}}@-o-keyframes uil-ripple{0%{width:0;height:0;opacity:0;margin:0}33%{width:44%;height:44%;margin:-22% 0 0 -22%;opacity:1}100%{width:88%;height:88%;margin:-44% 0 0 -44%;opacity:0}}@keyframes uil-ripple{0%{width:0;height:0;opacity:0;margin:0}33%{width:44%;height:44%;margin:-22% 0 0 -22%;opacity:1}100%{width:88%;height:88%;margin:-44% 0 0 -44%;opacity:0}}.uil-ripple-css{background:0 0;position:relative;width:200px;height:200px}.uil-ripple-css div{position:absolute;top:50%;left:50%;margin:0;width:0;height:0;opacity:0;border-radius:50%;border-width:12px;border-style:solid;-ms-animation:uil-ripple 2s ease-out infinite;-moz-animation:uil-ripple 2s ease-out infinite;-webkit-animation:uil-ripple 2s ease-out infinite;-o-animation:uil-ripple 2s ease-out infinite;animation:uil-ripple 2s ease-out infinite}.uil-ripple-css div:nth-of-type(1){border-color:#afafb7}.uil-ripple-css div:nth-of-type(2){border-color:#5cffd6;-ms-animation-delay:1s;-moz-animation-delay:1s;-webkit-animation-delay:1s;-o-animation-delay:1s;animation-delay:1s}
	</style>
-->
</head>
<body>
<div class="col-sm-6 col-sm-offset-3">

	<h1>Contact Form</h1>

	<!-- OUR FORM -->
	<form id="contactForm">

		<!-- NAME -->
		<div class="form-group">
			<label for="firstName">First Name</label>
			<input type="text" class="form-control" name="firstName" id="firstName" placeholder="Henry Pym">
			<span class="help-block"></span>
			<!-- errors will go here -->
		</div>

		<!-- NAME -->
		<div class="form-group">
			<label for="lastName">Last Name:</label>
			<input type="text" class="form-control" name="lastName" id="lastName" placeholder="Henry Pym">
			<span class="help-block"></span>
			<!-- errors will go here -->
		</div>

		<!-- NAME -->
		<div class="form-group">
			<label for="companyName">Company Name:</label>
			<input type="text" class="form-control" name="companyName" id="companyName" placeholder="Henry Pym">
			<span class="help-block"></span>
			<!-- errors will go here -->
		</div>

		<!-- NAME -->
		<div class="form-group">
			<label for="companyAddress">Company Address:</label>
			<input type="text" class="form-control" name="companyAddress" id="companyAddress" placeholder="Henry Pym">
			<span class="help-block"></span>
			<!-- errors will go here -->
		</div>

		<!-- NAME -->
		<div id="city-group" class="form-group">
			<label for="city">City:</label>
			<input type="text" class="form-control" name="city" id="city" placeholder="Henry Pym">
			<span class="help-block"></span>
			<!-- errors will go here -->
		</div>
<!--
		<div id="state-group" class="form-group">
      <label for="state">State</label>
      <select id="state" name="state" class="form-control">
        <option selected>Choose...</option>
        <option>...</option>
      </select>
    </div>
	-->

		<!-- EMAIL ADDRESS -->
		<div id="emailAddress-group" class="form-group">
			<label for="emailAddress">Email Address:</label>
			<input type="email" class="form-control" name="emailAddress" id="emailAddress" placeholder="rudd@avengers.com">
			<span class="help-block"></span>
			<!-- errors will go here -->
		</div>

		<!-- COMMENT -->
		<div id="comment-group" class="form-group">
			<label for="comment">Comment:</label>
			<input type="text" class="form-control" name="message" id="message" placeholder="Ant Man">
			<span class="help-block"></span>
			<!-- errors will go here -->
		</div>

		<div id="g-recaptcha-response" class="form-group">
			<div id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha" data-sitekey="public_key"></div>
			<span class="help-block"></span>
		</div>

<!--
		<div name="recaptcha" id="recaptcha-group" class="form-group">
			<div class="g-recaptcha" data-sitekey="6LePAV4UAAAAADzvGMCMHHJ47y9bUnmP4OhFJTax"></div>
		</div>
	-->

		<button type="button" id="sendMailBtn" data-loading-text="Please Wait..." class="btn btn-success form-control">Submit <span class="fa fa-arrow-right"></span></button>

	</form>

</div>
<script src="js/jquery-1.12.3.js"></script>
<!-- <script src="http://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/sweetalert/sweetalert.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>