Home Forums Porto Template FAQ’s How to setup Google Recaptcha in the Contact Form

This topic contains 0 replies, has 1 voice, and was last updated by  Support 1 year, 12 months ago. This post has been viewed 15696 times

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #10017919

    Support
    Keymaster

    Get reCAPTCHA API keys:

    For adding reCAPTCHA to your site, you need to register your site and get reCAPTCHA API keys.
    Register your site at Google from here – https://www.google.com/recaptcha/admin

    – Get your Site Key.
    Site key is used to display the reCAPTCHA widget.
    The code is in the pattern of the image below

    – Get your Secret Key.
    Secret key helps authorizes communication between your site and the reCAPTCHA server.
    The code is in the pattern of the image below

    For Basic Contact Form:

    – In contact-us.html:
    Insert HTML like the two images below:

    <div class="row mb-sm">
    	<div class="col-md-12">
    		<div class="g-recaptcha" data-sitekey="YOUR_RECAPTCHA_SITE_KEY"></div>
    	</div>
    </div>

    <script src='https://www.google.com/recaptcha/api.js' async defer></script>

    – In js/views/view.contact.js
    Insert like the image below:

    recaptcha: $form.find('#g-recaptcha-response').val()

    – Modify php/contact-form.php
    Copy all the code below and replace in php/contact-form.php
    IMPORTANT: Change “YOUR_SECRET_KEY” with your generated Google reCAPTCHA Secret Key.

    <?php
    /*
    Name: 			Contact Form
    Written by: 	Okler Themes - (http://www.okler.net)
    */
    ini_set('allow_url_fopen', true);
    
    session_cache_limiter('nocache');
    header('Expires: ' . gmdate('r', 0));
    
    header('Content-type: application/json');
    
    require_once('php-mailer/PHPMailerAutoload.php');
    
    if(isset($_POST['recaptcha']) && !empty($_POST['recaptcha'])) {
    
    	// Your Google reCAPTCHA generated Secret Key here
    	$secret = 'YOUR_SECRET_KEY';
    	
    	if( ini_get('allow_url_fopen') ) {
    		//reCAPTCHA - Using file_get_contents()
    		$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['recaptcha']);
    		$responseData = json_decode($verifyResponse);
    	} else if( function_exists('curl_version') ) {
    		// reCAPTCHA - Using CURL
    		$fields = array(
    	        'secret'    =>  $secret,
    	        'response'  =>  $_POST['recaptcha'],
    	        'remoteip'  =>  $_SERVER['REMOTE_ADDR']
    	    );
    
    	    $verifyResponse = curl_init("https://www.google.com/recaptcha/api/siteverify");
    	    curl_setopt($verifyResponse, CURLOPT_RETURNTRANSFER, true);
    	    curl_setopt($verifyResponse, CURLOPT_TIMEOUT, 15);
    	    curl_setopt($verifyResponse, CURLOPT_POSTFIELDS, http_build_query($fields));
    	    $responseData = json_decode(curl_exec($verifyResponse));
    	    curl_close($verifyResponse);
    	} else {
    		$arrResult = array ('response'=>'error','errorMessage'=>'You need CURL or file_get_contents() activated in your server. Please contact your host to activate.');
    		echo json_encode($arrResult);
    		die();
    	}
    
    	if($responseData->success) {
    
    		// Step 1 - Enter your email address below.
    		$email = 'you@domain.com';
    
    		// If the e-mail is not working, change the debug option to 2 | $debug = 2;
    		$debug = 0;
    
    		$subject = $_POST['subject'];
    
    		$fields = array(
    			0 => array(
    				'text' => 'Name',
    				'val' => $_POST['name']
    			),
    			1 => array(
    				'text' => 'Email address',
    				'val' => $_POST['email']
    			),
    			2 => array(
    				'text' => 'Message',
    				'val' => $_POST['message']
    			)
    		);
    
    		$message = '';
    
    		foreach($fields as $field) {
    			$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
    		}
    
    		$mail = new PHPMailer(true);
    
    		try {
    
    			$mail->SMTPDebug = $debug;                                 // Debug Mode
    
    			// Step 2 (Optional) - If you don't receive the email, try to configure the parameters below:
    
    			//$mail->IsSMTP();                                         // Set mailer to use SMTP
    			//$mail->Host = 'mail.yourserver.com';				       // Specify main and backup server
    			//$mail->SMTPAuth = true;                                  // Enable SMTP authentication
    			//$mail->Username = 'user@example.com';                    // SMTP username
    			//$mail->Password = 'secret';                              // SMTP password
    			//$mail->SMTPSecure = 'tls';                               // Enable encryption, 'ssl' also accepted
    			//$mail->Port = 587;   								       // TCP port to connect to
    
    			$mail->AddAddress($email);	 						       // Add another recipient
    
    			//$mail->AddAddress('person2@domain.com', 'Person 2');     // Add a secondary recipient
    			//$mail->AddCC('person3@domain.com', 'Person 3');          // Add a "Cc" address. 
    			//$mail->AddBCC('person4@domain.com', 'Person 4');         // Add a "Bcc" address. 
    
    			$mail->SetFrom($email, $_POST['name']);
    			$mail->AddReplyTo($_POST['email'], $_POST['name']);
    
    			$mail->IsHTML(true);                                  // Set email format to HTML
    
    			$mail->CharSet = 'UTF-8';
    
    			$mail->Subject = $subject;
    			$mail->Body    = $message;
    
    			$mail->Send();
    			$arrResult = array ('response'=>'success');
    
    		} catch (phpmailerException $e) {
    			$arrResult = array ('response'=>'error','errorMessage'=>$e->errorMessage());
    		} catch (Exception $e) {
    			$arrResult = array ('response'=>'error','errorMessage'=>$e->getMessage());
    		}
    
    		if ($debug == 0) {
    			echo json_encode($arrResult);
    		}
    
    	} else {
    		$arrResult = array ('response'=>'error','errorMessage'=>'Robot verification failed, please try again');
    		echo json_encode($arrResult);
    	}
    
    } else { 
    	$arrResult = array ('response'=>'error','errorMessage'=>'Please click on the reCAPTCHA box.');
    	echo json_encode($arrResult);
    }

    For Advanced Contact Form:

    – In contact-us-advanced.php:
    Remove and add HTML like the images below:
    CHANGE:

    TO:

    <div class="col-md-12">
    	<div class="row mb-sm">
    		<div class="col-md-12">
    			<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
    		</div>
    	</div>
    </div>

    – Add this script like image below:

    <script src='https://www.google.com/recaptcha/api.js' async defer></script>

    – In top of contact-us-advanced.php change ALL PHP code to this below:
    IMPORTANT: Change “YOUR_SECRET_KEY” with your generated Google reCAPTCHA Secret Key.

    <?php
    ini_set('allow_url_fopen', true);
    session_start();
    
    require_once('php/php-mailer/PHPMailerAutoload.php');
    
    if(isset($_POST['emailSent'])) {
    
    	if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
    
    		// Your Google reCAPTCHA generated Secret Key here
    		$secret = 'YOUR_SECRET_KEY';
    		
    		if( ini_get('allow_url_fopen') ) {
    			//reCAPTCHA - Using file_get_contents()
    			$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
    			$responseData = json_decode($verifyResponse);
    		} else if( function_exists('curl_version') ) {
    			// reCAPTCHA - Using CURL
    			$fields = array(
    		        'secret'    =>  $secret,
    		        'response'  =>  $_POST['g-recaptcha-response'],
    		        'remoteip'  =>  $_SERVER['REMOTE_ADDR']
    		    );
    
    		    $verifyResponse = curl_init("https://www.google.com/recaptcha/api/siteverify");
    		    curl_setopt($verifyResponse, CURLOPT_RETURNTRANSFER, true);
    		    curl_setopt($verifyResponse, CURLOPT_TIMEOUT, 15);
    		    curl_setopt($verifyResponse, CURLOPT_POSTFIELDS, http_build_query($fields));
    		    $responseData = json_decode(curl_exec($verifyResponse));
    		    curl_close($verifyResponse);
    		} else {
    			$arrResult = array ('response'=>'error','errorMessage'=>'You need CURL or file_get_contents() activated in your server. Please contact your host to activate.');
    			$serverError = true;
    		}
    
    		if(empty($serverError)) {
    
    			if($responseData->success) {
    
    				// Step 1 - Enter your email address below.
    				$email = 'you@domain.com';
    
    				// If the e-mail is not working, change the debug option to 2 | $debug = 2;
    				$debug = 0;
    
    				$subject = $_POST['subject'];
    
    				// Step 3 - Configure the fields list that you want to receive on the email.
    				$fields = array(
    					0 => array(
    						'text' => 'Name',
    						'val' => $_POST['name']
    					),
    					1 => array(
    						'text' => 'Email address',
    						'val' => $_POST['email']
    					),
    					2 => array(
    						'text' => 'Message',
    						'val' => $_POST['message']
    					),
    					3 => array(
    						'text' => 'Checkboxes',
    						'val' => implode($_POST['checkboxes'], ", ")
    					),
    					4 => array(
    						'text' => 'Radios',
    						'val' => $_POST['radios']
    					)
    				);
    
    				$message = '';
    
    				foreach($fields as $field) {
    					$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
    				}
    
    				$mail = new PHPMailer(true);
    
    				try {
    
    					$mail->SMTPDebug = $debug;                            // Debug Mode
    
    					// Step 3 (Optional) - If you don't receive the email, try to configure the parameters below:
    
    					//$mail->IsSMTP();                                         // Set mailer to use SMTP
    					//$mail->Host = 'mail.yourserver.com';				       // Specify main and backup server
    					//$mail->SMTPAuth = true;                                  // Enable SMTP authentication
    					//$mail->Username = 'user@example.com';                    // SMTP username
    					//$mail->Password = 'secret';                              // SMTP password
    					//$mail->SMTPSecure = 'tls';                               // Enable encryption, 'ssl' also accepted
    					//$mail->Port = 587;   								       // TCP port to connect to
    
    					$mail->AddAddress($email);	 						       // Add a recipient
    
    					//$mail->AddAddress('person2@domain.com', 'Person 2');     // Add another recipient
    					//$mail->AddCC('person3@domain.com', 'Person 3');          // Add a "Cc" address. 
    					//$mail->AddBCC('person4@domain.com', 'Person 4');         // Add a "Bcc" address. 
    
    					$mail->SetFrom($email, $_POST['name']);
    					$mail->AddReplyTo($_POST['email'], $_POST['name']);
    
    					$mail->IsHTML(true);                                  // Set email format to HTML
    
    					$mail->CharSet = 'UTF-8';
    
    					$mail->Subject = $subject;
    					$mail->Body    = $message;
    
    					// Step 4 - If you don't want to attach any files, remove that code below
    					if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
    						$mail->AddAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name']);
    					}
    
    					$mail->Send();
    
    					$arrResult = array ('response'=>'success');
    
    				} catch (phpmailerException $e) {
    					$arrResult = array ('response'=>'error','errorMessage'=>$e->errorMessage());
    				} catch (Exception $e) {
    					$arrResult = array ('response'=>'error','errorMessage'=>$e->getMessage());
    				}
    
    			} else {
    				$arrResult = array ('response'=>'error','errorMessage'=>'Robot verification failed, please try again');
    			}
    		}
    
    	} else { 
    		$arrResult = array ('response'=>'error','errorMessage'=>'Please click on the reCAPTCHA box.');
    	}
    
    }
    ?>

Viewing 1 post (of 1 total)