Create A Simple PHP Contact Form
Every site needs a contact form, but for a lot of beginners, the code can be a bit intimidating at first. In this article we are going to create a simple contact form that you can put on your website so your users have an easy way to get a hold of you.
Create the files
The first thing you need to do is create two new files: “contact.php” and “validate.class.php”.
Creating the contact form
Now lets open up “contact.php” and create a simple html contact form. Here is the html for your contact page. Note that we have also used the html for an entire page, including the head and body elements. If you just need the contact form, then only use the code inside of the <form></form> tags.
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple PHP Form Demo</title>
</head>
<body>
<form id="contact_form" method="post" action=".">
<p><label>Name:<br />
<input type="text" name="name" class="textfield" value="" />
</label></p>
<p><label>Email: <br />
<input type="text" name="email" class="textfield" value="" />
</label></p>
<p><label>Message: <br />
<textarea name="message" class="textarea" cols="45" rows="5"></textarea>
</label></p>
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
</form>
</body>
</html>
Alright, lets explain this a little bit. We have a form with it’s method set to post and it’s action set to “.” which may seem weird, but it’s a best coding practice not to leave this blank. What the period does, is tell the form to go back to this page after it is submitted.
We have also added Name and Email text inputs and a Message textarea. At the bottom you can see we have added a submit button to the form. Right now your form should look something like this:

Pretty plain and boring, but we will expand upon it!
Add some PHP
Now it’s time to start to make this form work. We are going to do that using PHP. First, go to the top of the “contact.php” file and paste the below code at the very top of the file, right above the doctype.
<?php
define("EMAIL", "youremail@yourdomain.com");
if(isset($_POST['submit'])) {
//include validation class
include('validate.class.php');
//assign post data to variables
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
}// end isset
?>
Lets walk through this line by line. First we define your email address as a constant. We do this, so it’s easy to change later on if we need to. Next there is an if statement that checks if the form has been submitted. Inside the if statement we include our validation class and then assign each form elements post value to a variable, just to make our lives a little easier.
Create our validation class
Now we need to jump over to our “validate.class.php” file and paste the code below:
<?php
class validate {
public $errors = array();
}// end class
First we create a new class named validate and then we create an array to hold our errors.
Now lets start adding some methods to our class. Add this code below the errors array:
public function validateStr($postVal, $postName, $min = 5, $max = 500) {
if(strlen($postVal) < intval($min)) {
$this->setError($postName, ucfirst($postName)." must be at least {$min} characters long.");
} else if(strlen($postVal) > intval($max)) {
$this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
}
}// end validateStr
This method is designed to validate more than one form element. It takes a string and checks to see if it is within the minimum and maximum string lengths. If it’s not, it logs an error message that we can retrieve. Lets take a look at this methods code:
Access: Public (this method can be accessed outside of this class)
It takes 4 Parameters
- $postVal: The post data for the form element
- $postName: The name of the form element
- $min: minimum amount of characters allowed
- $max: maximum amount of characters allowed
Return: Void (nothing)
Next lets create a method to validate our email addresses. This method validates an email address. It checks to see if an email is present and if it is, then it checks to make sure it’s a valid email address. It logs an error if either tests aren’t true. Paste in the below code:
public function validateEmail($emailVal, $emailName) {
if(strlen($emailVal) <= 0) {
$this->setError($emailName, "Please enter an Email Address");
} else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
$this->setError($emailName, "Please enter a Valid Email Address");
}
}// end validateEmail
Access: Public
It takes 2 Parameters
- $emailVal: The post value of your email address field
- $emailName: The name of the form element
Return: Void
Now we can start on our error handling functions. This method takes an error message and the form elements name and stores them in our errors array.
private function setError($element, $message) {
$this->errors[$element] = $message;
}// end logError
Access: Private (this method cannot be accessed from outside of this class)
It takes 2 Parameters
- $element: The name of the form element
- $message: The error message to be displayed
Return: Void
Now lets create a method that returns the error of a single form element. This takes the name of a form element and returns the error message for it or false if there is no error.
public function getError($elementName) {
if($this->errors[$elementName]) {
return $this->errors[$elementName];
} else {
return false;
}
}// end getError
Access: Public
It takes 1 Parameter
- $elementName: The name of the form element
Return: String – The error message for the given form element.
This method will displays all the forms errors as an html unordered list.
public function displayErrors() {
$errorsList = "<ul class=\"errors\">\n";
foreach($this->errors as $value) {
$errorsList .= "<li>". $value . "</li>\n";
}
$errorsList .= "</ul>\n";
return $errorsList;
}// end displayErrors
Access: Public
No Params
Return: String – A html list of the forms errors. The list has a CSS class named “errors”.
This method returns whether the form has errors.
public function hasErrors() {
if(count($this->errors) > 0) {
return true;
} else {
return false;
}
}// end hasErrors
Access: Public
No Params
Return: Boolean (true or false)
This method returns a string stating how many errors there were.
public function errorNumMessage() {
if(count($this->errors) > 1) {
$message = "There were " . count($this->errors) . " errors sending your message!\n";
} else {
$message = "There was an error sending your message!\n";
}
return $message;
}// end hasErrors
Access: Public
No Params
Return: String – stating the number of errors the form has.
Now that we are done with our simple validation class lets open our “contact.php” file back up and put this class to work. Lets start out back at the top of this file. Locate this line:
$message = trim($_POST['message']);
and paste this code in after it:
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);
if(!$v->hasErrors()) {
$header = "From: $email\n" . "Reply-To: $email\n";
$subject = "Contact Form Subject";
$email_to = EMAIL;
$emailMessage = "Name: " . $name . "\n";
$emailMessage .= "Email: " . $email . "\n\n";
$emailMessage .= $message;
@mail($email_to, $subject ,$emailMessage ,$header );
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
$nameErr = $v->getError("name");
$emailErr = $v->getError("email");
$messageErr = $v->getError("message");
}//end error check
Now lets break this code down. First we create a new object $v. Then we validate our name, email and message fields with our new class methods. Next we use an if statement to check if the form has any errors with our “$v->hasErrors()” method. If the form doesn’t have any errors, we send the email message. If it does, we use some of our class methods to get the number of errors message, a list of all the errors and we also get errors for each individual form element.
Now since we have all of these errors stored in variables, we need to display them. I simply added this code at the top of the form to display a gerneral error message:
<?php echo $message_text; echo $errors; ?>
and then I added this code to our name field to get the error message for just that element:
<?php echo $nameErr; ?>
Then you can do the same for you email and message fields as well.
Now you can pick and choose how you want to display error messages on your form.

Now we can add some CSS to the form to make it look a little more stylish.
body {
margin:0;
padding:0;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
background-color:#101a25;
color:#fff;
}
#contact_form_wrap {
margin:0 auto;
margin-top:50px;
padding:10px;
width:350px;
}
.message {
font-weight:bold;
}
.errors {
color:#af1010;
}
label {
font-weight:bold;
}
.textfield {
padding:5px 0 0 3px;
width:297px;
height:20px;
border: 1px solid #e9e9e9;
background-color:#303942;
color:#fff;
}
.textarea {
padding:3px;
width:294px;
height:144px;
border: 1px solid #e9e9e9;
background-color:#303942;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
color:#fff;
}
.button {
padding:3px 0 5px 0;
width:75px;
height:25px;
border: none;
background-color:#303942;
font-weight:bold;
cursor:pointer;
color: #fff;
font-family:Arial, Helvetica, sans-serif;
}
.button:hover {
background-color:#f1f1f1;
color: #333;
}

Here is the complete code with comments:
contact.php
<?php
define("EMAIL", "youremail@yourdomain.com");
if(isset($_POST['submit'])) {
include('validate.class.php');
//assign post data to variables
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);
if(!$v->hasErrors()) {
$header = "From: $email\n" . "Reply-To: $email\n";
$subject = "Contact Form Subject";
$email_to = EMAIL;
$emailMessage = "Name: " . $name . "\n";
$emailMessage .= "Email: " . $email . "\n\n";
$emailMessage .= $message;
//use php's mail function to send the email
@mail($email_to, $subject ,$emailMessage ,$header );
//grab the current url, append ?sent=yes to it and then redirect to that url
$url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
header('Location: '.$url."?sent=yes");
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
$nameErr = $v->getError("name");
$emailErr = $v->getError("email");
$messageErr = $v->getError("message");
}//end error check
}// end isset
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex, nofollow"/>
<title>Simple PHP Form Demo | Box Model Junkie</title>
<style type="text/css">
body {
margin:0;
padding:0;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
background-color:#101a25;
color:#fff;
}
#contact_form_wrap {
margin:0 auto;
margin-top:50px;
padding:10px;
width:350px;
}
.message {
font-weight:bold;
}
.errors {
color:#af1010;
}
label {
font-weight:bold;
}
.textfield {
padding:5px 0 0 3px;
width:297px;
height:20px;
border: 1px solid #e9e9e9;
background-color:#303942;
color:#fff;
}
.textarea {
padding:3px;
width:294px;
height:144px;
border: 1px solid #e9e9e9;
background-color:#303942;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
color:#fff;
}
.button {
padding:3px 0 5px 0;
width:75px;
height:25px;
border: none;
background-color:#303942;
font-weight:bold;
cursor:pointer;
color: #fff;
font-family:Arial, Helvetica, sans-serif;
}
.button:hover {
background-color:#f1f1f1;
color: #333;
}
</style>
</head>
<body>
<div id="contact_form_wrap">
<span class="message"><?php echo $message_text; ?></span>
<?php echo $errors; ?>
<?php if(isset($_GET['sent'])): ?><h2>Your message has been sent</h2><?php endif; ?>
<form id="contact_form" method="post" action=".">
<p><label>Name:<br />
<input type="text" name="name" class="textfield" value="<?php echo htmlentities($name); ?>" />
</label><br /><span class="errors"><?php echo $nameErr; ?></span></p>
<p><label>Email: <br />
<input type="text" name="email" class="textfield" value="<?php echo htmlentities($email); ?>" />
</label><br /><span class="errors"><?php echo $emailErr ?></span></p>
<p><label>Message: <br />
<textarea name="message" class="textarea" cols="45" rows="5"><?php echo htmlentities($message); ?></textarea>
</label><br /><span class="errors"><?php echo $messageErr ?></span></p>
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
</form>
</div>
</body>
</html>
validate.class.php
<?php
class validate {
// ---------------------------------------------------------------------------
// paramaters
// ---------------------------------------------------------------------------
/**
* Array to hold the errors
*
* @access public
* @var array
*/
public $errors = array();
// ---------------------------------------------------------------------------
// validation methods
// ---------------------------------------------------------------------------
/**
* Validates a string
*
* @access public
* @param $postVal - the value of the $_POST request
* @param $postName - the name of the form element being validated
* @param $min - minimum string length
* @param $max - maximum string length
* @return void
*/
public function validateStr($postVal, $postName, $min = 5, $max = 500) {
if(strlen($postVal) < intval($min)) {
$this->setError($postName, ucfirst($postName)." must be at least {$min} characters long.");
} else if(strlen($postVal) > intval($max)) {
$this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
}
}// end validateStr
/**
* Validates an email address
*
* @access public
* @param $emailVal - the value of the $_POST request
* @param $emailName - the name of the email form element being validated
* @return void
*/
public function validateEmail($emailVal, $emailName) {
if(strlen($emailVal) <= 0) {
$this->setError($emailName, "Please enter an Email Address");
} else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
$this->setError($emailName, "Please enter a Valid Email Address");
}
}// end validateEmail
// ---------------------------------------------------------------------------
// error handling methods
// ---------------------------------------------------------------------------
/**
* sets an error message for a form element
*
* @access private
* @param string $element - name of the form element
* @param string $message - error message to be displayed
* @return void
*/
private function setError($element, $message) {
$this->errors[$element] = $message;
}// end logError
/**
* returns the error of a single form element
*
* @access public
* @param string $elementName - name of the form element
* @return string
*/
public function getError($elementName) {
if($this->errors[$elementName]) {
return $this->errors[$elementName];
} else {
return false;
}
}// end getError
/**
* displays the errors as an html un-ordered list
*
* @access public
* @return string: A html list of the forms errors
*/
public function displayErrors() {
$errorsList = "<ul class=\"errors\">\n";
foreach($this->errors as $value) {
$errorsList .= "<li>". $value . "</li>\n";
}
$errorsList .= "</ul>\n";
return $errorsList;
}// end displayErrors
/**
* returns whether the form has errors
*
* @access public
* @return boolean
*/
public function hasErrors() {
if(count($this->errors) > 0) {
return true;
} else {
return false;
}
}// end hasErrors
/**
* returns a string stating how many errors there were
*
* @access public
* @return void
*/
public function errorNumMessage() {
if(count($this->errors) > 1) {
$message = "There were " . count($this->errors) . " errors sending your message!\n";
} else {
$message = "There was an error sending your message!\n";
}
return $message;
}// end hasErrors
}// end class
From here you can easily extend this class to validate websites and phone numbers. Just duplicate the validateEmail method, but change the regex to what you need.
Hope this tutorial helps and please let me know about any bugs / errors you find.




Create A Simple PHP Contact Form
When form is submitted I get a blank page with character...
Create A Simple PHP Contact Form
I am trying to CAPTCHA to the validation page but am...
Create A Simple PHP Contact Form
I use a simpler form of this until now that looks...