integrating recaptcha v2 in php contact form

the mail() function

Moderators: egami, macek, gesf

Post Reply
asshok
New php-forum User
New php-forum User
Posts: 2
Joined: Sun May 16, 2021 1:02 am

Sun May 16, 2021 1:14 am

Hello,

I have a contact form and I am trying to implement recapcha into it. Recaptcha works in itself but it doesn't works for some reason when I insert it in the form.

Here is the form

Code: Select all

<form action="assets/mail/contact.php" method="POST" class="contact-form">
    <div class="col-md-12">
                                <div class="row">
                                    <div class="form-group">
                                        <input class="form-control" id="name" name="name" placeholder="Name" type="text">
                                        <span class="alert-error"></span>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <input class="form-control" id="email" name="email" placeholder="Email*" type="email">
                                        <span class="alert-error"></span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <input class="form-control" id="phone" name="phone" placeholder="Phone" type="text">
                                        <span class="alert-error"></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <div class="row">
                                    <div class="form-group comments">
                                        <textarea class="form-control" id="comments" name="comments" placeholder="Tell Us About Project *"></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-12">
        <!-- Google reCAPTCHA block -->
        <div class="g-recaptcha" data-sitekey="my_site_key_here"></div>
      </div>
                            <!-- Alert Message -->
                            <div class="col-md-12 alert-notification">
                                <div id="message" class="alert-msg"></div>
                            </div>

                            <div class="col-md-12">
                                <div class="row">
                                    <button type="submit" name="submit" id="submit">
                                        Send Message <i class="fa fa-paper-plane"></i>
                                    </button>
                                </div>
                            </div>
                            
    </form>
and here is form processing page

Code: Select all

<?php
if(!$_POST) exit;


  
        


// Email address verification, do not edit.
function isEmail($email) {
	return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}

if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");

$name     = $_POST['name'];
$email    = $_POST['email'];
$comments = $_POST['comments'];


if(trim($name) == '') {
	echo '<div class="alert alert-error">Enter your name.</div>';
	exit();
} else if(trim($email) == '') {
	echo '<div class="alert alert-error">Enter your email.</div>';
	exit();
} else if(!isEmail($email)) {
	echo '<div class="alert alert-error">Enter a valid email address.</div>';
	exit();

}
else if(trim($comments) == '') {
	echo '<div class="alert alert-error">Enter your message.</div>';
	exit();
}

     
if(get_magic_quotes_gpc()) {
	$comments = stripslashes($comments);
}


  // reCAPTCHA validation
            if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
                // Google secret API
                $secretAPIkey = 'my_secret_key_here';
                // reCAPTCHA response verification
                $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$_POST['g-recaptcha-response']);
                // Decode JSON data
                $response = json_decode($verifyResponse);
               	if($response->success){
//send mail 
   
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe@yourdomain.com";

//$address = "example@mydmain.net";
$address = "example@mydmain.net";


// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."

// Example, $e_subject = '$name . ' has contacted you via Your Website.';

$e_subject = 'Contact Form';


// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.

$e_body = "You have been contacted by $name, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";

$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );

$headers = "From: care@domain.ru" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;

if(mail($address, $e_subject, $msg, $headers)) {

	// Email has sent successfully, echo a success page.

	echo "<div class='alert alert-success'>";
	echo "<h3>Message sent.</h3>";
	echo "</div>";

 } 
}
				else {
                        echo "<div class='alert alert-error'>";
	                    echo "<p>Robot verification failed, please try again.</p>";
	                    echo "</div>";
                    }       
            } else{ 
			echo "<div class='alert alert-error'>";
	                    echo "<p>Plese check on the reCAPTCHA box.</p>";
	                    echo "</div>";
             } 
        	
					
       
    
I have a strong feeling that g-recaptcha-response is NULL for some reason.
I have included <script src="https://www.google.com/recaptcha/api.js" async defer></script> in the page.
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 418
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Sun May 16, 2021 2:56 am

The following might help you :

Code: Select all

if (hash_equals($_SESSION['token'], $data['token'])) {
    /* The Following to get response back from Google recaptcha */
    $url = "https://www.google.com/recaptcha/api/siteverify";

    $remoteServer = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_URL);
    /*
     * g-response is from $data['response'] that was sent over using FETCH
     */
    $response = file_get_contents($url . "?secret=". PRIVATE_KEY . "&response=" . $data['response'] . "&remoteip=" . $remoteServer);
    $recaptcha_data = json_decode($response);
    /* The actual check of the recaptcha */
    if (isset($recaptcha_data->success) && $recaptcha_data->success === TRUE) {
        /*
         * If token matches and ReCaptcha is valid then send to an email
         * php script or php class. I personally use Swiftmailer, but you can use
         * another 3rd Party Mailer or write you own email script (I wouldn't
         * recommend it).
         */
        $data['message'] =
            '<html lang="en">' .
            '<body style=\'background: #eee;\'>' .
            '<p style="font-size: 1.8em; line-height: 1.5;">' . $data['name'] . '<br>' . $data['email'] . '<br>' . $data['phone'] . '<br>' . $data['website'] . '<br> Subject of Email is ' . $data['reason'] . '</p>' .
            '<p style="font-size: 1.6em; line-height: 1.5;">' . $data['comments'] . '</p>' .
            '<p style="font-size: 1.4em; line-height: 1.5;">Thank You, for taking your time to contact me! I will get back to you as soon as I can.<br> Best regards, John Pepp</p>' .
            '</body>' .
            '</html>';
        $send = new sendMail();
Life is a fig newton of your imagination! https://www.miniaturephotographer.com
asshok
New php-forum User
New php-forum User
Posts: 2
Joined: Sun May 16, 2021 1:02 am

Sun May 16, 2021 8:46 am

Thanks everyone. I have sorted it out. There was div disbalance above and below the form.
jackslesly19
New php-forum User
New php-forum User
Posts: 4
Joined: Sun May 23, 2021 5:50 pm

Mon May 31, 2021 4:07 am

I noticed that you’ll be are usually legitimately interested in this type of...read more
Post Reply