Easy PHP script

Originally written by James Richardson on 06/09/2010

Let your visitors contact you easily by using a PHP email form

Sending email through a web based contact form is what everyone needs for their website. Programs like FormMail use long and cumbersome codes to acheive the simplest results. With the following code, you will be able to send emails to your email address through your contact page and create an auto responder that emails the person that filled out the form. The following link is the zipped version of the code that you can save and utilize immediately with your website. Click here to download the script

Validating the form data

The following code comes before the header of the html document. This code will validate the user input. The good thing about this code is that you can duplicate the code and insert different Regular expressions to validate different types of input.

//This section must be placed before the header section of the HTML document. 
//This is for input validation to see if the correct information was entered into the form.
if (isset($_REQUEST['submitted'])) {
	// Initialize error array.
	$errors = array();
	// Check for a proper name
	if (!empty($_REQUEST['name'])) {
		$name = $_REQUEST['name'];
		$pattern = "/^[a-zA-Z0-9\_]{2,20}/";
        // This is a regular expression that checks if the name is valid characters
		if (preg_match($pattern,$name)){ $name = $_REQUEST['name'];}
		else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
	} else {$errors[] = 'You forgot to enter your Name.';}
	//Check for a valid email address
	if (!empty($_REQUEST['email'])) {
		$email = $_REQUEST['email'];
		$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
        //This is a common email regular expression designed to check if the email address is valid
		if (preg_match($pattern,$email)){ $email = $_REQUEST['email'];}
		else{ $errors[] = 'Your Email was invalid.';}
	} else {$errors[] = 'You forgot to enter your Email.';}
	//This the comment the user sent to the contact
	if (!empty($_REQUEST['comment'])) {
		$comment = $_REQUEST['comment'];
		$comment = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', 
        '<a href="$1" target="_blank" class="none">$1</a>', $comment);//changes  urls into links
		$comment = nl2br($comment);//This inserts <br />when the return key is pressed
	} else {$errors[] = 'You forgot to enter your Comment.';}
	// This matches the Verification box to prevent spammers from emailing you
	if (!empty($_REQUEST['very'])) {
		$very = $_REQUEST['very'];
		$rand = $_REQUEST['rand'];
		if ($very == $rand){ /*Do nothing*/}
		else{ $errors[] = 'The verification code you entered was wrong.';}
	} else {$errors[] = 'You forgot to enter the verification code.';}

If the form has no errors

If there are no errors, the form will go through, executing the php email function. The email function is written twice. One is for the person who filled out the form and the other is for the person who the user is trying to contact. The email function will have the message that the user typed into the form sent to them. A simple responder is set up for the user to get in the mail showing that the email they sent went through and that they will be contacted soon.

 
/*
If everything validates correctly. 
The following will send emails to the contact and the person filling out the form
*/
if (empty($errors)) { 
		
	$from = "From: Our Site!";//Site name
	$to = "john@doe.com";//Contact email address
	$subject = "Admin - Our Site! Comment from " . $name . "";
	
	//The following is the Message that the is sent to the contect
	$message1 = "Message from " . $name . " 
	Email: ".$email." 
	Message: ".stripslashes($comment)."";
	mail($to,$subject,$message1,$from);
	//End of contact info
	
	//The is the response email that confirms that the email was sent to the contact.
	$subject2 = "Thank You for your comment at Our Site!";	
	$message2= "Thank You " . $name . " for your comment.
	Please allow me 48 hours to respond to your comment.
	Thank You for your concern.
	John Doe
	john@doe.com
	
	** Your Response Information that you want the person who emailed you to see.
	";
	mail($email,$subject2,$message2,$from);
	//End of auto responder
}
}
//End of validation script. 

Styles

The following code is just for styling the form and the errors. Typically you will want to style the error messages so the user can see that the inputed the wrong data.

<style type="text/css"> 
body {
	background: #00002B;
	font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
	color: #CCC;
}
h1 {
	color: #F93;	
}
h1 {
	color: #F60;	
}
li {
	list-style: disc;
	color: #FF3737;
}
input {
	padding: 2px;
}
#container {
	width: 700px;
	background-color:#036;
	padding: 10px 30px 30px 30px;
	margin: 0 auto; 
	border: 2px solid #000000;
	text-align:center;
}
.security img{
	padding: 0px;
}
.security input{
	margin: 0px 30px 0px 0px;
}
</style>

Catch all Errors and Post them for the user to see

The following code will execute if the validation of the form fails. There is a simple foreach function that will display each error that occurred. If there are no errors, the user will be notified that the message went through.

<?php 

if (isset($_REQUEST['submitted'])) {
// Print any error messages.	
	if (!empty($errors)) { 
		
		echo '<hr />
		<h3>The following occurred:</h3>
		<ul>';
		
		foreach ($errors as $msg) { // Print each error.
			echo '<li>'. $msg . '</li>';
		}
		echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';
	}else{
		echo '<hr /><h3 align="center">Your mail was sent. Thank you!</h3><hr />';
	}
}
//End of errors array
?>

The Form

The following section of the code is just a basic form made in html. You can add or subtract from this area. When you make a new form field, keep in mind that the name of the field must match the name in the form validation section. If the validation sction is not created for the new inputs you create, the form will assume that the content of the field is correct. Otherwise you will need to add a validation script in the validation section of the script.

<!--
After this is the form section that the user will fill out for the contact information.
You will want to place this code where you want your form to appear.
-->
<form onsubmit="<?php $_SERVER['PHP_SELF']; ?>" method="post">
Name: <br />
<input name="name" id="name" type="text" size="40" /><br />
Email Address: <br />
<input name="email" id="email" type="text" size="40" /><br />
Comment: <br />
<textarea name="comment" cols="70" rows="10" id="comment"></textarea>
<br />
    
    <div class="security">
    <?php
	/*
	this is the security section that the user will need 
	to fill out for preventing spammers from emailing you.
	*/
	
    $num =  md5(uniqid(rand(), true)); //For random  numbers and text
    $num = substr($num, 0, 5); //Limits the amount of characters in the string - Default is 5
    
	// Security question text box and Image
    echo 'Type the text found in the box: <br />
    <input name="very" value="" type="text" />
    <input name="rand" value="' . $num . '" type="hidden" />';
       
	//below is the image script for generating the random image.
    create_image($num);
    print "<img src=image.png?".date("U").">";
    
	function  create_image($num){
		$im = @imagecreate(100, 22) or die("Cannot Initialize new GD image stream"); 
        // this creates the image . . . dimensions are 100px x 22px
		$background_color = imagecolorallocate($im, 100, 100, 100);  
        // grey color . . . this accepts RGB color code
		$black = imagecolorallocate($im, 0, 0, 0);      
        // black color . . . Image background color . . . this accepts RGB color code
		$red = imagecolorallocate($im, 255, 0, 0);      
        // red color . . . this accepts RGB color code
		imagerectangle ($im, 0, 0, 99, 21, $red);		
        // Image border color
		imagestring($im, 5, 29, 3, $num, $black);		
        // Properties of this line (Image size, Text size 
        (1, 2, 3, 4, 5), Left padding, top padding, Text to be displayed, Text color)
		imagepng($im,"image.png");						
        // Image size and name that is written
		imagedestroy($im);								
        // ends creating any mor images
    }
	//End of the security script
    ?>
    </div>
    
<br />
<input name="submitted" value="submitted" type="hidden" />
<input name="submit" value="Submit" type="submit" />
<input name="reset" value=" Reset " type="reset" />
</form>
<!--
This is the end of the contact form.
-->

The Whole Script

The next section is the whole script. This script will make life simple and give you the ability to customize your form with little code and less headache than other email form scripts. This script is given as is and can be customized to your specifications. There is no warrantee with this code. If you hyave any trouble, please contact me and I will help you with the code.

<?php 
/***************************************************************************************
                      James Richardson's Easy PHP Email Script
This email script is an open source script designed for you to edit the source code 
to suit your needs. You will want to style this code according to your website needs.
This script is given "as is" with no warrantees. Simple insert this script into 
your php page according to the notes within this scrtipt and you will be able to 
recieve email from your contact form and send a responder to the person that filled 
out the form. For further inquiries on this script visit the absolutewebdev.com 
contact page and contact me.
****************************************************************************************/




/*
This section must be placed before the header section of the HTML document. 
This is for input validation to see if the correct information was entered into the form.
*/
if (isset($_REQUEST['submitted'])) {
	// Initialize error array.
	$errors = array();
	// Check for a proper name
	if (!empty($_REQUEST['name'])) {
		$name = $_REQUEST['name'];
		$pattern = "/^[a-zA-Z0-9\_]{2,20}/";
        // This is a regular expression that checks if the name is valid characters
		if (preg_match($pattern,$name)){ $name = $_REQUEST['name'];}
		else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
	} else {$errors[] = 'You forgot to enter your Name.';}
	//Check for a valid email address
	if (!empty($_REQUEST['email'])) {
		$email = $_REQUEST['email'];
		$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
        //This is a common email regular expression designed to check if the email address is valid
		if (preg_match($pattern,$email)){ $email = $_REQUEST['email'];}
		else{ $errors[] = 'Your Email was invalid.';}
	} else {$errors[] = 'You forgot to enter your Email.';}
	//This the comment the user sent to the contact
	if (!empty($_REQUEST['comment'])) {
		$comment = $_REQUEST['comment'];
		$comment = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', 
        '<a href="$1" target="_blank" class="none">$1</a>', $comment);
        //changes  urls into links
		$comment = nl2br($comment);//This inserts <br />when the return key is pressed
	} else {$errors[] = 'You forgot to enter your Comment.';}
	// This matches the Verification box to prevent spammers from emailing you
	if (!empty($_REQUEST['very'])) {
		$very = $_REQUEST['very'];
		$rand = $_REQUEST['rand'];
		if ($very == $rand){ /*Do nothing*/}
		else{ $errors[] = 'The verification code you entered was wrong.';}
	} else {$errors[] = 'You forgot to enter the verification code.';}
//End of validation	

		
/* 
If everything validates correctly. 
The following will send emails to the contact and the person filling out the form
*/
if (empty($errors)) { 
		
	$from = "From: Our Site!";//Site name
	$to = "john@doe.com";//Contact email address
	$subject = "Admin - Our Site! Comment from " . $name . "";
	
	//The following is the Message that the is sent to the contect
	$message1 = "Message from " . $name . " 
	Email: ".$email." 
	Message: ".stripslashes($comment)."";
	mail($to,$subject,$message1,$from);
	//End of contact info
	
	//The is the response email that confirms that the email was sent to the contact.
	$subject2 = "Thank You for your comment at Our Site!";	
	$message2= "Thank You " . $name . " for your comment.
	Please allow me 48 hours to respond to your comment.
	Thank You for your concern.
	John Doe
	john@doe.com
	
	** Your Response Information that you want the person who emailed you to see.
	";
	mail($email,$subject2,$message2,$from);
	//End of auto responder
}
}
//End of validation script. All the code befor this should be placed before the "<!DOCTYPE" tag
?>

<!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>James’s Easy PHP contact mail script</title>

<style type="text/css"> 
body {
	background: #00002B;
	font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
	color: #CCC;
}
h1 {
	color: #F93;	
}
h1 {
	color: #F60;	
}
li {
	list-style: disc;
	color: #FF3737;
}
input {
	padding: 2px;
}
#container {
	width: 700px;
	background-color:#036;
	padding: 10px 30px 30px 30px;
	margin: 0 auto; 
	border: 2px solid #000000;
	text-align:center;
}
.security img{
	padding: 0px;
}
.security input{
	margin: 0px 30px 0px 0px;
}
</style>
</head>

<body>

<div id="container">
<h1>James Richardson’s</h1> 
<h2>Easy PHP contact mail script</h2>

<?php 
/*
The following code will produce the error massage that 
informs the use of what was inputted wrong in the form.
You will place this section where you want your errors to be seen.
*/
if (isset($_REQUEST['submitted'])) {
// Print any error messages.	
	if (!empty($errors)) { 
		
		echo '<hr />
		<h3>The following occurred:</h3>
		<ul>';
		
		foreach ($errors as $msg) { // Print each error.
			echo '<li>'. $msg . '</li>';
		}
		echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';
	}else{
		echo '<hr /><h3 align="center">Your mail was sent. Thank you!</h3><hr />';
	}
}
//End of errors array
?>


<!--
After this is the form section that the user will fill out for the contact information.
You will want to place this code where you want your form to appear.
-->
<form onsubmit="<?php $_SERVER['PHP_SELF']; ?>" method="post">
Name: <br />
<input name="name" id="name" type="text" size="40" /><br />
Email Address: <br />
<input name="email" id="email" type="text" size="40" /><br />
Comment: <br />
<textarea name="comment" cols="70" rows="10" id="comment"></textarea>
<br />
    
    <div class="security">
    <?php
	/*
	this is the security section that the user will need 
	to fill out for preventing spammers from emailing you.
	*/
	
    $num =  md5(uniqid(rand(), true)); //For random  numbers and text
    $num = substr($num, 0, 5); //Limits the amount of characters in the string - Default is 5
    
	// Security question text box and Image
    echo 'Type the text found in the box: <br />
    <input name="very" value="" type="text" />
    <input name="rand" value="' . $num . '" type="hidden" />';
       
	//below is the image script for generating the random image.
    create_image($num);
    print "<img src=image.png?".date("U").">";
    
	function  create_image($num){
		$im = @imagecreate(100, 22) or die("Cannot Initialize new GD image stream"); 
        // this creates the image . . . dimensions are 100px x 22px
		$background_color = imagecolorallocate($im, 100, 100, 100);  
        // grey color . . . this accepts RGB color code
		$black = imagecolorallocate($im, 0, 0, 0);      
        // black color . . . Image background color . . . this accepts RGB color code
		$red = imagecolorallocate($im, 255, 0, 0);      
        // red color . . . this accepts RGB color code
		imagerectangle ($im, 0, 0, 99, 21, $red);		
        // Image border color
		imagestring($im, 5, 29, 3, $num, $black);		
        // Properties of this line (Image size, Text size 
        1, 2, 3, 4, 5), Left padding, top padding, Text to be displayed, Text color)
		imagepng($im,"image.png");						
        // Image size and name that is written
		imagedestroy($im);								
        // ends creating any mor images
    }
	//End of the security script
    ?>
    </div>
    
<br />
<input name="submitted" value="submitted" type="hidden" />
<input name="submit" value="Submit" type="submit" />
<input name="reset" value=" Reset " type="reset" />
</form>
<!--
This is the end of the contact form.
-->

</div>
<!-- End of the container -->
</body>
</html>

Get a copy of My Banjo Buddy!


Recent articles



Top


100% Browser Compliant
         
100% Valid HTML5