How can I add a contact page to send user feedback to my email box?

This is a ques­tion I get from a lot from students:

Here’s my solution:

  1. Cre­ate a contact.php page.
  2. Add the fol­low­ing HTML form inside the HTML body tag:
What's your name?
Valid E-mail please
Write your message here
  1. Now above the form add the PHP nec­es­sary to mail the user’s input to your email
<?php
if(isset($_POST['send'])) {
    $to = "yournamel@yourname.com";
    $subject = trim($_POST['name']) . " has filled out the Web Site Contact Form";
    $from = trim($_POST['email']);
    $headers = "From: $from";
    $message = trim(stripslashes($_POST['message']));
    mail($to, $subject,$message, $headers);
}
?>
  1. Replace the email here with your email: $to = “youremail@youremail.com”;
  2. FTP contact.php to your server
  3. Go to yourdomain.com/contact.php
    • This is assum­ing you FTP’d contact.php to the root of your site
  4. Fill out the form
  5. Sub­mit it

That’s it! You should receive the form’s feed­back in your email.

A sample image of your filled out form

A sam­ple image of your filled out form

The email you receive will look something like this

The email you receive will look some­thing like this

Let’s make some improve­ments to this sim­ple con­tact form

First of all, let’s make our bor­ing form look a lit­tle less bor­ing. Just cre­ate a file called main.css and add the CSS below to main.css.

/******* FORM *******/ 

#frmContact {
	padding: 0 10px 10px;
}

#frmContact label {
	display: block;
	color: #797979;
	font-weight: 700;
	line-height: 1.4em;
}

#frmContact input {
	width: 220px;
	padding: 6px;
	color: #949494;
	font-family: Arial, Verdana, Helvetica, sans-serif;
	font-size: 11px;
	border: 1px solid #cecece;
}

#frmContact input.error {
	background: #ccc;
	border-color: #333;
}

#frmContact textarea {
	width: 550px;
	height: 80px;
	padding: 6px;
	color: #adaeae;
	font-family: Arial, Verdana, Helvetica, sans-serif;
	font-style: italic;
	font-size: 12px;
	border: 1px solid #cecece;
}

#frmContact textarea.error {
	background: #ccc;
	border-color: #333;
}

#frmContact div {
	margin-bottom: 15px;
}

#frmContact div span {
	margin-left: 10px;
	color: #b1b1b1;
	font-size: 11px;
	font-style: italic;
}

#frmContact div span.error {
	color: #e46c6e;
}

#frmContact #send {
	color: #000;
	font-weight: 700;
	font-style: normal;
	border: 0;
	cursor: pointer;
	background-color: #ccc;
}

#frmContact #send:hover {
	background: aqua;
}

/* error code */
	#error {
	margin-bottom: 0;
	border: 1px solid #333;
	margin-left: 10px;
}

#error ul {
	list-style: square;
	padding: 5px;
	font-size: 11px;
}

#error ul li {
	list-style-position: inside;
	line-height: 1.6em;
}

#error ul li strong {
	color: #e46c6d;
}

#error.valid ul li strong {
	color: #ccc;
	font-weight: bold;
}
/******* /FORM *******/
Oooh. Look how much nicer our form looks with some CSS

Oooh. Look how much nicer our form looks with some CSS

Now we need to add some PHP val­i­da­tion. This is very impor­tant and ensures that the user fills our form out and we don’t receive an empty email.

Add the fol­low­ing PHP above your DOCTYPE

<?php
	function validateName($name){
		//if it's NOT valid
		if(strlen($name) < 4)
			return false;
		//if it's valid
		else
			return true;
	}
	function validateEmail($email){
		return preg_match("^[a-zA-Z0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$^", $email);
	}
	function validatePasswords($pass1, $pass2) {
		//if DOESN'T MATCH
		if(strpos($pass1, ' ') !== false)
			return false;
		//if are valid
		return $pass1 == $pass2 && strlen($pass1) > 5;
	}
	function validateMessage($message){
		//if it's NOT valid
		if(strlen($message) < 10)
			return false;
		//if it's valid
		else
			return true;
	}
?>

Now change the code above the form to the code I have added in the box below.

(Make sure you read the com­ments. I wrote them for you!)

<?php
// here we check to see if the form has been sent AND then we call 3 functions
// if any of the functions return true it means the form wasn't filled out properly
// and we inform the user of what they need to fix
// it should be noted that this validation won't be seen unless JavaScript is turned off in the browser
// it should also be noted that you SHOULD ALWAYS HAVE SERVER SIDE VALIDATION because JavaScript can be turned off but PHP can not be turned off.
if( isset($_POST['send']) && (!validateName($_POST['name']) || !validateEmail($_POST['email']) || !validateMessage($_POST['message']) ) ) { ?>

        
    <?php if(!validateName($_POST['name'])) { ?>
  • Invalid Name: Please enter a name with more than 3 letters
  • <?php } ?> <?php if(!validateEmail($_POST['email'])) { ?>
  • Invalid E-mail: Type a valid e-mail please
  • <?php } ?> <?php if(!validateMessage($_POST['message'])) { ?>
  • Invalid message: Type a message with at least with 10 letters
  • <?php } ?>
<?php } elseif(isset($_POST['send'])) { ?>
  • Thank You!
<?php if(isset($_POST['send'])) { $to = "youremail@youremail.com"; // don't forget to change this line to your email address! $subject = trim($_POST['name']) . " has filled out the Web Site Contact Form"; $from = trim($_POST['email']); $headers = "From: $from"; $message = trim(stripslashes($_POST['message'])); mail($to, $subject,$message, $headers); } ?> <?php } ?>

Now in order to see this PHP val­i­da­tion code in full effect, you need to turn JavaScript off

How do I turn JavaScript off?

Here’s an easy way. Let’s use the Fire­fox browser as it has great web devel­oper tools to work with. You need to add a plu­gin to Fire­fox. If you don’t know how to add plu­g­ins to Fire­fox, you don’t know what you are miss­ing. Here’s a tuto­r­ial to get you started.

Add the Web Devel­oper addon to Firefox

When it’s added, Fire­fox should now have this cool toolbar.

Chris Pederick's Web Developer Toolbar

Chris Pederick’s Web Devel­oper Toolbar

This video will show you how to use Web Devel­oper. It’s a bit blurry but you should get the idea. Turn JavaScript off by Dis­able > Dis­able JavaScript > All JavaScript

Please remem­ber to turn JavaScript back on when your fin­ished. I for­get all the time and for a few sec­onds I think the world will end. Save your­self this trou­ble and turn JavaScript back on.

Now fill out your form and hit the sub­mit but­ton. You should see some­thing like the image below.

The form showing PHP validation

The form show­ing PHP validation

Now the last thing we need to do is add some JQuery validation.

Add the fol­low­ing SCRIPT links to point the PHP page to the JavaScript files.


The first script tag points to an online repos­i­tory for JQuery.

The sec­ond JavaScript points to a file on your server. Make sure to cre­ate validation.js and add the fol­low­ing JavaScript to it:

$(document).ready(function(){
	//global vars
	var form = $("#frmContact");
	var name = $("#name");
	var nameInfo = $("#nameInfo");
	var email = $("#email");
	var emailInfo = $("#emailInfo");
	//var pass1 = $("#pass1");
//	var pass1Info = $("#pass1Info");
	//var pass2 = $("#pass2");
	//var pass2Info = $("#pass2Info");
	var message = $("#message");
	var messageInfo = $("#messageInfo");

	//On blur
	name.blur(validateName);
	email.blur(validateEmail);
	//pass1.blur(validatePass1);
	//pass2.blur(validatePass2);
	//On key press
	name.keyup(validateName);
	//pass1.keyup(validatePass1);
	//pass2.keyup(validatePass2);
	message.keyup(validateMessage);
	//On Submitting
	form.submit(function(){
		if(validateName() & validateEmail() & validateMessage())
			return true
		else
			return false;
	});

	//validation functions
	function validateEmail(){
		//testing regular expression
		var a = $("#email").val();
		var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
		//if it's valid email
		if(filter.test(a)){
			email.removeClass("error");
			emailInfo.text("Valid E-mail please!");
			emailInfo.removeClass("error");
			return true;
		}
		//if it's NOT valid
		else{
			email.addClass("error");
			emailInfo.text("Type a valid e-mail please.");
			emailInfo.addClass("error");
			return false;
		}
	}
	function validateName(){
		//if it's NOT valid
		if(name.val().length < 4){
			name.addClass("error");
			nameInfo.text("Please enter a name with more than 3 letters.");
			nameInfo.addClass("error");
			return false;
		}
		//if it's valid
		else{
			name.removeClass("error");
			nameInfo.text("What's your name?");
			nameInfo.removeClass("error");
			return true;
		}
	}
	function validatePass1(){
		var a = $("#password1");
		var b = $("#password2");

		//it's NOT valid
		if(pass1.val().length <5){
			pass1.addClass("error");
			pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
			pass1Info.addClass("error");
			return false;
		}
		//it's valid
		else{
			pass1.removeClass("error");
			pass1Info.text("At least 5 characters: letters, numbers and '_'");
			pass1Info.removeClass("error");
			validatePass2();
			return true;
		}
	}
	function validatePass2(){
		var a = $("#password1");
		var b = $("#password2");
		//are NOT valid
		if( pass1.val() != pass2.val() ){
			pass2.addClass("error");
			pass2Info.text("Passwords doesn't match!");
			pass2Info.addClass("error");
			return false;
		}
		//are valid
		else{
			pass2.removeClass("error");
			pass2Info.text("Confirm password");
			pass2Info.removeClass("error");
			return true;
		}
	}
	function validateMessage(){
		//it's NOT valid
		if(message.val().length < 10){
			message.addClass("error");
			messageInfo.addClass("error");
			messageInfo.text("Please type at least 10 characters");
			return false;
		}
		//it's valid
		else{
			message.removeClass("error");
			messageInfo.removeClass("error");
			return true;
		}
	}
});

Upload your new JavaScript to the remote server and once again test your con­tact form by fill­ing it out. Make sure you are deal­ing with a refreshed browser win­dow and that you have turned JavaScript back on. You will never see JQuery work with JavaScript turned off because… JQuery is JavaScript.

After hit­ting sub­mit you should see the fol­low­ing:

JQuery validation

JQuery val­i­da­tion

Now we are fin­ished. If you want to improve on the code, try the following:

  • Make sure all your CSS is external
  • Use PHP include state­ments to exter­nal­ize all the code above the DOCTYPE

That’s all I have for this one folks. Please let me know if I made any mis­takes or if there is a way to make this better.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>