Jump to content

Validating This Contact Form

- - - - -

  • Please log in to reply
8 replies to this topic

#1
daraclare

daraclare

    Learning Programmer

  • Members
  • PipPipPip
  • 44 posts
Hi, I'm hoping someone can help me add some validation code to this simple contact form (it's free from this site: A Nice & Simple Contact Form (Downloadable) | CSS-Tricks)

Unfortunately, it's a tiny bit too simple for me as I need to be sure people input their emails and phone numbers correctly so we can contact them. Emails especially. Any help would be appreciated!

My contact.html is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">


<head>
	<title>A Nice & Simple Contact Form</title>
	
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	
	<link rel="stylesheet" type="text/css" href="style.css" />
</head>


<body>


	<div id="page-wrap">


		<img src="images/title.gif" alt="A Nice & Simple Contact Form" /><br /><br />
		<p>By <a href="http://css-tricks.com">CSS-Tricks</a></p>
		
		<p>There are a million contact form examples on the web, why this one? Because it's SIMPLE, it's FREE, it WORKS, it's VALID, and it's primarily styled with CSS.</p>
		
		<p>If you are trying to contact CSS-Tricks, DO NOT USE THIS FORM. This is just an example, my real <a href="http://css-tricks.com/contact/">contact form is here</a>.</p>
		
		<p><a href="http://css-tricks.com/examples/NiceSimpleContactForm.zip">[DOWNLOAD THIS EXAMPLE]</a></p>
				
		<div id="contact-area">
			
			<form method="post" action="contactengine.php">
				<label for="Name">Name:</label>
				<input type="text" name="Name" id="Name" />
				
				<label for="City">City:</label>
				<input type="text" name="City" id="City" />
	
				<label for="Email">Email:</label>
				<input type="text" name="Email" id="Email" />
				
				<label for="Message">Message:</label><br />
				<textarea name="Message" rows="20" cols="20" id="Message"></textarea>


				<input type="submit" name="submit" value="Submit" class="submit-button" />
			</form>
			
			<div style="clear: both;"></div>
			
			<p>Check out a <a href="http://css-tricks.com/examples/NiceSimpleContactForm2">version of this</a> with SPAM protection.</p>
		
		</div>
	
	</div>


</body>


</html>

The file contactengine.php looks like this:

<?php
$EmailFrom = "name@gmail.com";$EmailTo = "CHANGE-THIS@YOUR-DOMAIN.com";$Subject = "Nice & Simple Contact Form by CSS-Tricks";$Name = Trim(stripslashes($_POST['Name'])); $Tel = Trim(stripslashes($_POST['Tel'])); $Email = Trim(stripslashes($_POST['Email'])); $Message = Trim(stripslashes($_POST['Message'])); 
// validation$validationOK=true;if (!$validationOK) {  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";  exit;}
// prepare email body text$Body = "";$Body .= "Name: ";$Body .= $Name;$Body .= "\n";$Body .= "Tel: ";$Body .= $Tel;$Body .= "\n";$Body .= "Email: ";$Body .= $Email;$Body .= "\n";$Body .= "Message: ";$Body .= $Message;$Body .= "\n";
// send email $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page if ($success){  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";}else{  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";}?>


#2
mikenco

mikenco

    Newbie

  • Members
  • Pip
  • 5 posts
Not sure if there is ANY perfect way to prevent against some users, but after using contact forms for years, I find that tweaked version of this works good. It's a self contained php form, which you can use as a javascript pop-up from any web page.

Read through the source code carefully and personalise it.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">


<head>


<title>Contact Us</title>



<!-- METADATA -->


<script type="text/JavaScript">

<!--

//pass min and max -measured against window width

function P7_MinMaxW(a,b){

	var nw="auto",w=document.documentElement.clientWidth;

	if(w>=b){nw=b+"px";}if(w<=a){nw=a+"px";}return nw;

}

//-->

</script>

<!--[if lte IE 6]>

<style type="text/css">

#pagewrapper {width:expression(P7_MinMaxW(750,750));}

#container {height: 1%;}

</style>

<![endif]-->


<style type="text/css">

<!--

.NewLine {

	padding: 10px;

}

body {

	font-family: Verdana, Arial, Helvetica, sans-serif;

}

.LabelField {

	font-size: 12px;

	float: left;

	width: 100px;

	text-align: right;

}

.txtNorm {

	font-size: 12px;

}

.txtTiny {

	font-size: 10px;

}

#EnquiryDetails {

	font-family: Verdana, Arial, Helvetica, sans-serif;

}

.txtTitle {

	font-size: 18px;

	color: #999999;

}

.EntryField {

	margin-left: 110px;

	width: 350px;

}

#centre_content {

	width: 475px;

	border: thin solid #CCCCCC;

	padding: 10px;

	background-image: background.jpg);

}

.txtSmallNote {

	font-size: 10px;

}

.radioButtons {

	font-size: 9px;

}

-->

</style>

</head>

<body>

<div id="centre_content">


<?php


// where to send e-mail to

$to = 'YOUREMAIL@SOMETHING.COM'; //i.e. bloggs@whatever.com

//$to2 = 'YOUREMAIL2@SOMETHING.COM'; // uncomment if you want other recips (but see further down too)

//$to3 = 'YOUREMAIL3@SOMETHING.COM'; // uncomment if you want other recips (but see further down too)


// This will remove HTML tags, javascript sections

// and white space. It will also convert some

// common HTML entities to their text equivalent.

$search = array ('@<script[^>]*?>.*?</script>@si', // Strip out javascript

                 '@<[\/\!]*?[^<>]*?>@si',          // Strip out HTML tags

                 '@([\r\n])[\s]+@',                // Strip out white space

                 '@&(quot|#34);@i',                // Replace HTML entities

                 '@&(amp|#38);@i',

                 '@&(lt|#60);@i',

                 '@&(gt|#62);@i',

                 '@&(nbsp|#160);@i',

                 '@&(iexcl|#161);@i',

                 '@&(cent|#162);@i',

                 '@&(pound|#163);@i',

                 '@&(copy|#169);@i',

                 '@&#(\d+);@e');                    // evaluate as php


$replace = array ('',

                 '',

                 '\1',

                 '"',

                 '&',

                 '<',

                 '>',

                 ' ',

                 chr(161),

                 chr(162),

                 chr(163),

                 chr(169),

                 'chr(\1)');


// declare and sanitise values

$FirstName = preg_replace($search, $replace, $_POST['FirstName']);

$LastName = preg_replace($search, $replace, $_POST['LastName']);

$PrefContact = preg_replace($search, $replace, $_POST['PrefContact']);

$PhoneNumber = preg_replace($search, $replace, $_POST['PhoneNumber']);

$EmailAddress = preg_replace($search, $replace, $_POST['EmailAddress']);

$EnquiryDetails = preg_replace($search, $replace, $_POST['EnquiryDetails']);


$mydate = date ( 'l, F d Y g:i A',time()+240 );



// e-mail subject (variable param)

$subject = "Generic Contact Form (from: $FirstName $LastName)";


// e-mail message

$message = "Generic Contact Form Submission:\r\n"

."----------------------------------------------------------------\r\n"

."Name: $FirstName $LastName\r\n"

."This person would prefer to be contacted by: $PrefContact\r\n"

."Phone: $PhoneNumber\r\n"

."Email: $EmailAddress\r\n\r\n"

."Referrer: $Referrer\r\n\r\n"

."Message: \r\n$EnquiryDetails\r\n"

."----------------------------------------------------------------\r\n"

."Submitted: $mydate\r\n"

."From IP: {$_SERVER['REMOTE_ADDR']}\r\n"

."Form Address: {$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}\r\n"

."----------------------------------------------------------------\r\n";


$headers = "From: $FirstName $LastName <$EmailAddress>\n"

."Reply-To: $EmailAddress\n"

."X-Mailer: PHP/".phpversion();


// check for validation, then send the e-mail


if (!empty($FirstName)){

	if ($FirstName==$LastName){echo "No Spam Please!"; die;}

	}




if(empty($FirstName) || empty($LastName) || empty($PhoneNumber) || empty($EmailAddress) || empty($EnquiryDetails)) {


?>


<div class='txtTitle'>Contact Us</div>


<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST">


<div class="NewLine">

	<div class="LabelField">Title:</div>

     <div class="EntryField">

	 <select name="select">

      <option value="Not Specified">select..</option>

      <option value="Mr">Mr</option>

      <option value="Mrs">Mrs</option>

      <option value="Ms">Ms</option>

      <option value="Miss">Miss</option>

    </select>

	</div>

	</div>


<div class="NewLine">

	<div class="LabelField">First Name:</div>

	<div class="EntryField"><input name="FirstName" type="text" id="FirstName" value="<?php echo $_POST['FirstName'];?>" size="20" />

	</div>

</div>


<div class="NewLine">

	<div class="LabelField">Last Name:</div>

	<div class="EntryField"><input name="LastName" type="text" id="LastName" value="<?php echo $_POST['LastName'];?>" size="20" />

	</div>

</div>


<div class="NewLine">

	<div class="LabelField">Phone Number:</div>

	<div class="EntryField"><input name="PhoneNumber" type="text" id="PhoneNumber" value="<?php echo $_POST['PhoneNumber'];?>" size="20" />

	<span class="txtSmallNote">←</span><input name="PrefContact" type="radio" value="Phone" checked="checked" class="radioButtons" /> <span class="txtSmallNote">(preferred contact method)</span>	</div>

</div>


<div class="NewLine">

	<div class="LabelField">Email Address:</div>

	<div class="EntryField"><input name="EmailAddress" type="text" id="EmailAddress" value="<?php echo $_POST['EmailAddress'];?>" size="20" />

	<span class="txtSmallNote">←</span><input name="PrefContact" type="radio" value="Email" />

	</div>

</div>	


<div class="NewLine">

	<div class="LabelField">Enquiry Details:</div>

	<div class="EntryField">

	  <textarea name="EnquiryDetails" cols="30" rows="5" id="EnquiryDetails"><?php echo $_POST['EnquiryDetails'];?></textarea>

	</div>

</div>


<div class="NewLine">

	<div class="LabelField"> </div>

	<div class="EntryField">

	<input name="Referrer" id="Referrer" type="hidden" value="<?php echo($_COOKIE['ref']); ?>" />

	<input name="submit" type="submit" class="submit" value="Submit" />

	</div>

	</div>

</form>


<div class="txtTiny" align="right">Your IP: <?php echo $_SERVER[REMOTE_ADDR]?></div>


<?php


} elseif(!ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $EmailAddress)) {

echo "<p>ERROR: Please enter a valid e-mail address.</p>";

} else {


mail( $to, $subject, $message, $headers );

// mail( $to2, $subject, $message, $headers ); //uncomment if you want more than one recip.

// mail( $to3, $subject, $message, $headers ); //uncomment if you want more than one recip.

?>


<div class='txtTitle'>Message Sent!</div>


<p>

<div class="txtNorm">

Thank you <?php echo $FirstName. " " . $LastName; ?> for your enquiry.

<br /><br />

We will get back to you shortly.</div>


  <?php 

	}

?>

  

<div class="txtTiny" align="right">©<?php echo date("Y"); ?> - Powered by <a href="http://www.YOURDOMAIN.co.uk" target="_blank">YOUR DOMAIN</a></div>

</div> 

    <!-- end centre content -->

	

</body>

</html>



P.s. There is a bit in there about cookie refs. It can track who sent your user to the form. But more on that if you need it.

Hope this helps.

Mike

#3
Jmancuso

Jmancuso

    Newbie

  • Members
  • PipPipPip
  • 37 posts
ahh i love this topic, the thread is a bit old but there are people who are going to look at this for in the future. the tip for validating what the user inputs in php is with a built in function called ereg() or eregi(). these are called regular expressions and aree not too confusing once you get the hang of it.

lets give an example:



//lets say you have an input feild called email


echo "<input type='text' name='email' /> ";


//now to make it a little easier, lets make the html a little more php friendly


$email = $_POST['email'];


//perfect! now lets make a regular expression. pay attention!


$confirmation = ereg("^.+@.+\..+", $email);


//above is the email confirmation, this ensures that the email address should look pretty similar to an email address.

//now lets make an if statement:


if ($confirmation){

     //insert all your database insertion here.

}



that is basic email validation. its not that confusing. ill even tell you what it means in human language.
starting in the ereg() function:

the carat(^) simply means look for - the ".+" means all white space and that @ symbol means @. so so far we have "look for all whitespace, and an @ symbol" now after that @ symbol, we have once again the ".+" signs. which of course means all white space. the "\" symbol means literally. so "\." means litterally look for a period. and then you know what the ".+" means.

so in human terms: "look for(^) any whitespace (.+), an @ symbol(@), more whitespace(.+), a period (\.) and then more whitespace(.+)"
in display terms it looks for: whitespace@whitespace.whitespace. now obviously this isnt perfect.

we can make it better:
quick definition: ereg() means regular expressions, eregi() means regular expression non case sensitive, so if you want it to looks for [a-z], it would also look for [A-Z]


//this is what mark zuckerberg used when he was writing code for facebook, he used pearl as a language of chocie but this is the php version:


$email = $_POST['email'];

$confirmation = eregi("^.+@harvard.edu", $email);


//means look for(^) any whitespace(.+) @ harvard.edu. its that simple.


//and when he expanded into other universities:

$confirmation = eregi("^.+@( harvard | standford | columbia ).edu", $email);


//by now you should know what the pipe symbol (|) means, it just means OR. like if (a == a || a==b){}



i dont want to make this post too longg but:

if you want to validate numbers:


$homephone_confirmation = ereg("^[0-9]{0,1}\-?[0-9]{0,2}\-?[0-9]{0,2}\-?[0-9]{0,3}", $homephone);


//this will check a phone number in this order: 1-482-555-9837 and if they do or dont put hyphens, it doesnt matter.

//if you have a confirmation of a city and state like this: Raleigh North Carolina, 11762 (not sure why you would) but:


$address_confirmation = eregi("^[a-z]\,?[a-z]\,?[0-9]{0,4}", $address)

//this will look for that format, and a 5 digit zipcode at the end (im pretty sure all zip codes are 5 digits)


i hope this helps anyone who looks at in the future

#4
Orjan

Orjan

    Writes binary right handed and hex left handed

  • Moderators
  • 3,299 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#
Um... .+ does not mean "whitespace". Whitespace is characters that is not visible, as tabs, spaces etc.
The atom . says match on any character and the quantifier + says 0 or more times, so .+ means match on any length of non-whitespace characters.

By the way, ereg and eregi etc is deprecated from PHP 5.3 and the preg functions is the adviced functions to use.
__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall

#5
Jmancuso

Jmancuso

    Newbie

  • Members
  • PipPipPip
  • 37 posts
yeah but i tried to be as simple as possible in explaining it

#6
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
  • Programming Language:Java, C#, PHP
  • Learning:C, C++, C#, PHP, Transact-SQL, Assembly, Scheme

Quote

the carat(^) simply means look for - the ".+" means all white space and that @ symbol means @. so so far we have "look for all whitespace, and an @ symbol" now after that @ symbol, we have once again the ".+" signs. which of course means all white space. the "\" symbol means literally. so "\." means litterally look for a period. and then you know what the ".+" means.

Sorry but .+ does not mean all whitespace. The . means match any one character and + means match the previous expression 0 or more times. If you wanted to match all whitespace \s+ is what you are looking for.

Also "the carat(^) simply means look for -" is wrong. The carat means match preceding pattern at beginning of the string.

#7
Jmancuso

Jmancuso

    Newbie

  • Members
  • PipPipPip
  • 37 posts
not sure what you guy's arguments are. i think you guys are confusing whitespace with blank space. whitespace is the equivalent of saying anything.

definition - In computer science, whitespace is any single character or series of characters that represents horizontal or vertical space in typography

#8
Orjan

Orjan

    Writes binary right handed and hex left handed

  • Moderators
  • 3,299 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#
I know one thing, and that is that you (Jmanusco) haven't understood the meaning of whitespace.
White space IS the area between words and other visual characters.

Whitespace character - Wikipedia, the free encyclopedia says clearly: (which you got your quote from)

Quote

The most common whitespace characters may be typed via the space bar or the Tab key. Depending on context, a line-break generated by the Return key (Enter key) may be considered whitespace as well.
a bit further down on the very same page:

Quote

The C language defines whitespace to be "... space, horizontal tab, new-line, vertical tab, and form-feed".

__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall

#9
Jmancuso

Jmancuso

    Newbie

  • Members
  • PipPipPip
  • 37 posts
ahh. re-learn something new everyday. when i learn from a book i guess its easy to miss-communicate myself.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users