Feedback on Contact Form

So I have created a contact form that originally did not have any mechanism in sending out the email with whatever the user inputted in the fields. I have added it in here along with ReCaptcha check. I would like to get some feedback on the code, especially that I am looking to upgrading the email body to send out emails that are styled and look better.

<?php
$yourEmail = "email@email.com"; // <== Your Email
$secret = 'LALALALAALALALALALALA'; // <==Your recaptcha Privte Key
$errors         = array();  	// array to hold validation errors
$data 			= array(); 		// array to pass back data

// validate the variables ======================================================
	// if any of these variables don't exist, add an error to our $errors array

	// ---------------------Start the recaptcha ------------------------------------//
	if(isset($_POST['g-recaptcha-response']) && ($_POST['g-recaptcha-response'])){
					session_start();
			$ip = $_SERVER['REMOTE_ADDR'];
			$captcha = $_POST['g-recaptcha-response'];
			$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip=$ip");
			$result = json_decode($response,TRUE);
					if($result['success'] == 1){
							$_SESSION['result'] = $result['success'];
							}
	// --------------------End Of the Captcha Check------------------------- //

	if (empty($_POST['name']))
		$errors['name'] = 'Name is required.';

	if (empty($_POST['email']))
		$errors['email'] = 'Email is required.';

	if (empty($_POST['phone']))
		$errors['phone'] = 'Phone is required.';

		// ---------------------Start the recaptcha ------------------------------------//

		if(!isset($_SESSION['result']) || $_SESSION['result'] == 0){
			 	$formerrors[] =  'Captcha Error';
		}

		// --------------------End Of the Captcha Check------------------------- //

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

	// if there are any errors in our errors array, return a success boolean of false
	if ( ! empty($errors)) {

		// if there are items in our errors array, return those errors
		$data['success'] = false;
		$data['errors']  = $errors;
	} else {

		// if there are no errors process our form, then return a message

		// DO ALL YOUR FORM PROCESSING HERE
		// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

		// show a message of success and provide a true success variable
		$data['success'] = true;
		$data['message'] = 'Success!';
	}

	// return all our data to an AJAX call
	echo json_encode($data);

	//Start of Sending Email
	$to = $yourEmail;	// Email to receive contacts
	$from = $email;
	$subject = 'Contact Form Email : ' . $title;
	$message = '<style>
							body{background-color:#fefefe}
							.email-style {padding: 30px;background: #fafafa;font-size: 18px;border: 1px solid #ddd;width: 60%;margin: auto;}
							p {padding: 15px 0px;}
							</style>

							<div class="email-style"><p> '.$title . '</p>

							<p>Contact Full Name : '.$name . ' </p>

							<p>Contact Email : '.$email . ' </p>

							<p>Contact Phone Number : '.$phone . '</p>

							<p>Message : '.$message . ' </p>

							<p>Cheers,</p>
							<p>'.$name.' Via Contact Form</p></div>';

	$headers = "From: $from\n";
	$headers .= "MIME-Version: 1.0\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\n";
		 if( mail($to, $message, $headers) ){
					echo "sent";
					session_unset();
					session_destroy();
				} else {
								 echo "The server failed to send the message. Please try again later.";
							}
						}
?>

Check the empty expression because I think it should be replaced with count.

Nope, !empty($errors) is the same as count($errors) > 0.

1 Like

I would suggest the following:

  1. Check and fix the indentation of your code, it’s hard to read

  2. Do not use file_get_contents to load from the network, as some hosts have this disabled. Use curl instead.

  3. Check all details you can check locally first (name etc), and immediately fail if any of those details fails. And only if they succeed check the captcha, that prevents round trips to recaptcha for nothing.

  4. Really check variables, your script allows hello there as an email address, while clearly it’s not

  5. Don’t use == to compare variables; instead of == 1 use === true

1 Like

Instead of using the PHP mail() I would suggest using PHPMailer or SwiftMailer as PHP mail() can sometimes be rather unpredictable.

1 Like

Another thing to note is that session_destroy should suffice. You don’t need session_unset.

Can’t see your form front end but i’d also add in some html5 validation on the fields. Never rely on them alone but i think it’s worth just adding ‘required’ and ‘type=email’ just to catch a few user errors before the form is submitted. It saves a page reload for example if they just mistype an email and miss the @ symbol or something. A pageload on a dodgy mobile signal could cost you a completed form.

If the client side check fails or is bypassed you’ll still pick it up with your serverside validation. Having said that get the serverside validation working perfectly and then add in the front end bits so you know you are covered.

hth

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.