Create A Simple PHP Contact Form

A once a week, free newsletter with handpicked Web Design, Development and Freelance jobs.

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.

A once a week, free newsletter with handpicked Web Design, Development and Freelance jobs.

S

h

a

r

e

  • Share this post on Delicious
  • StumbleUpon this post
  • Share this post on Digg
  • Tweet about this post
  • Share this post on Mixx
  • Share this post on Technorati
  • Share this post on Facebook
  • Share this post on NewsVine
  • Share this post on Reddit
  • Share this post on Google
  • Share this post on LinkedIn

About the author

Nate Smith has written 22 articles for Box Model Junkie

I am a 28 year old designer / developer from Peoria, IL who is very into PHP, WordPress, Django and jQuery. I have a huge passion for the web and love learning new things. You can follow me on twitter @imns81

87 Responses to "Create A Simple PHP Contact Form"

  • B.Czar™ 08:13 PM 26/7/2010

    An endearing, no-nonsense and simple approach to PHP forms. The code commentary is especially helpful and the code itself laid out clearly.

    Thank you for sharing.

    • Box Model Junkie 08:43 PM 26/7/2010

      Glad you liked it. Thanks for checking it out.

  • Charles 01:13 PM 30/7/2010

    Bliss…. finally someone that approaches this clearly. Thank you.

  • Brian 11:54 PM 06/8/2010

    Its too bad it doesn’t work!

    • Nate Smith 08:06 PM 07/8/2010

      Hey Brian,

      Can you tell me what you are having a problem with and maybe I can help you out.

      • Brian 06:55 PM 19/8/2010

        I get error messages in every place that I enter the code as well as inside the form elements itself:
        Notice: Undefined variable: nameErr in C:\Program Files (x86)\EasyPHP-5.3.2i\www\portfolio13\contact.php on line 80

        I get the same results from copying and pasting your finished code and posting it on my server.

      • Brian 12:52 AM 03/9/2010

        Either I’m an idiot or this tutorial doesn’t work because I’ve tried everything with no luck

      • Nate Smith 10:13 PM 10/9/2010

        Not sure why you are having trouble with that, but you could try wrapping nameErr in an isset function. ex: if(isset($nameErr)) { echo $nameErr; }

        You will have to do the same for the other vars that throw errors

      • Brian 07:04 PM 13/9/2010

        That clears all the error message off my site. But I still cant get it to work. None of the fields preform an error check. It also does it send off an email after clicking the submit button.

  • choen 06:53 PM 12/8/2010

    nice, but im confuse if success send massage? nothing sing

    • Nate Smith 02:48 AM 19/8/2010

      I didn’t add that to the script. I will update the article when I have a little free time, but what you want to do is do a redirect back to the same page after you send the email.

  • Mat3o 11:29 AM 18/8/2010

    You should change to and it’ll work )).
    Sorry for my english.

  • Mat3o 11:30 AM 18/8/2010

    @up
    action=”.” to action=”content.php” in form paragraph

    • Nate Smith 02:50 AM 19/8/2010

      The “.” is actually a best practice that mean submit to this page, but if it isn’t working on your setup you should definitely change it to fit your needs.

  • Eis 10:58 AM 27/8/2010

    Hi, Nate! Thanks a million for this tutorial. My comment is the same as Choen’s. I guess I’ll just have to wait till you update this article. Can’t wait!

  • Nate Smith 04:04 AM 31/8/2010

    I updated the code so it displays a simple error message after you submit it. What I did was to do a header redirect back to the form after it’s been submitted and append ?sent=yes to the url. Then I check for the persons of the GET variable sent and it it’s there the form displays the thank you message.

  • Gal 09:03 PM 07/9/2010

    Hello. I want to say that this is great tutorial, not just for contact form but explaining a lot of things (for me :)) in PHP. May I ask if it is possible to be explained how can I use this form with PHPmailer and especially the SMTP option. I’ve tried couple of times but probably I am mixing variables or just putting the code on the wrong row. Thanks in advance.

    • Nate Smith 10:15 PM 10/9/2010

      You would replace PHP’s mail function with your PHPmailer code. Here is the mail function: @mail($email_to, $subject ,$emailMessage ,$header ); … that’s what actually sends the email.

  • L.Care 10:10 PM 07/9/2010

    Hi mate, I have used your code and it’s brilliant… just what i’m looking for.

    One thing though. My email address (formated a.bcdef@domain.prefix) is not recognised as valid.

    This appears to be soley because of the single letter before the first . Any advice?

    • L.Care 10:19 PM 07/9/2010

      ^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}

      actually solved this for me removing the first [^0-9] from the line.

      • Nate Smith 10:16 PM 10/9/2010

        Yeah, you just need to find a new regex that meets your needs. Looks like you have a good start.

      • nfo 12:31 AM 22/1/2011

        best practice should be to use php filter function:

        $email = ‘joe@example.com’;

        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo “This ($email) email address is considered valid.”;
        }

        anyway good post..

    • Nate Smith 02:17 PM 28/1/2011

      @nfo, that is true, but not everyone has access to php 5 and filter_var. You are right though, that is a better way to do it. Thanks for pointing that out!

  • Ron 11:46 PM 01/10/2010

    How about including a series of radio buttons, a select dropdown and a checkbox in this example?

    • Nate Smith 02:52 PM 14/10/2010

      Hey Ron, maybe one of these days I will have some free time and update this post with some more examples.

  • peter 03:23 AM 01/12/2010

    Absolutely awesome, well put together and so simple, clutter free. I am adapting this for one of my projects, I spent a whole afternoon looking then came across your site, thanks so much :)

  • richard 09:24 AM 05/5/2011

    great tutorial done really well :) is there any way to keep php seperate so you have “contact.html” “proccess.php”, and “validate.class.php” its just i dont want to change the file types im worried there will be an affect in the SEO google rank, and also would be very gratefull if you could give me tips on how.
    thanks for any help and for this blog just what i was looking for

  • snipes 02:13 AM 09/6/2011

    Nice tutorial , I could not find better than this one , well explained .. yes I had some errors too
    for the undefined variable but I managed to get ride of them with isset, yes im a noob to php .. oh yessss thx !

  • Kieran 02:14 AM 05/10/2011

    Hi Nate,

    Everything here looks very solid. The only thing I’m having trouble understanding is how you get the input values of the HTML form to correspond with “$postVal” and “$postName”? If you could explain this to me I would be very grateful as it is the only thing I am having a problem understanding. Thanks in advance, Kieran.

  • Max H 03:17 PM 13/10/2011

    Thanks for the very well explained starter validation class.

    Has allowed me to create my own customised version without getting too confused :P

  • Asad 05:31 PM 29/10/2011

    Really nice. Just change to action=”"

  • geoff 11:57 PM 09/11/2011

    My Submit button just sends me up one level (from ‘/form/contact.php’ to ‘/form/’) and gives a 404 error

    What am I doing wrong?

    • Nate Smith 01:36 AM 10/11/2011

      You just need to change your forms action to “/form/contact.php” so it submits to the contact form.

      • geoff 12:45 AM 11/11/2011

        Thanks, is there an easy way to add more fields? I’m running into problems there

  • sanjeevmc 02:29 PM 15/2/2012

    its not working…..

    also what does it mean by action=”.”?
    pl explain or let me know if you have updated version.

    thanks in advance

    • Nate Smith 01:13 PM 27/4/2012

      The action=”.” just means submit the form to the current page.

  • Zam 02:18 PM 16/2/2012

    Is it important to have the following code:

    in the form field’s “value” attribute?

    I want to put something else like “Enter Your Name”, instead. Can I do that without the code breaking? or is it absolutely necessary?

  • Zam 06:17 PM 16/2/2012

    Thanks for taking the time to write this awesome tutorial! I just finished configuring it and was wondering how would I set more than 1 email recipient?

  • shan 03:37 AM 20/2/2012

    Hello, I have this form working on my site, but when I hit submit, I go to a blank page, but my URL is right.

    I am having a hard time trouble shooting this.

    Any ideas? I would expect to be redirected to the message stating the form was submitted… This tutorial has been AWESOME in helping me understand, I am soooo close :)

    • Nate Smith 01:12 PM 27/4/2012

      You can change the forms action to the URL of your contact form. That should fix the problem.

      • Mike 10:03 PM 09/7/2012

        Yeah that was my challenge so thanks for posting that. I had to put the entire URL in (http://…) it was quite frustrating! thanks for this killer form though. Even non-coder like me can make it work! I’ve been looking all over for a form exactly like this.

  • Laurie 09:02 PM 25/3/2012

    I have designed an form that is part of a webpage and I’m trying to figure out how to validate it.

    Your example is the easiest I’ve come across, but I still can’t alter your code to successfully work with my form.

    Also when I save the page with the .php extension the page is blank and firefox asks me if I want to run the script? Even when it on my ftp.

    Any help would be greatly welcomed.

    Laurie

    • Nate Smith 01:11 PM 27/4/2012

      Your server has to be able to run PHP scripts. Try looking into xampp for local development.

  • Todd M. 08:29 AM 23/4/2012

    Great PHP tut. Thanks for posting, love the process.

  • Mandy 09:33 PM 26/4/2012

    Hi Nate,

    I have an issue I can’t figure out. The form works awesome, I absolutely love it, until I try to add a phone number field. After that I get an error: Warning: Cannot modify header information – headers already sent by (… mobile/validate.class.php:1). The email goes through just fine. I receive it, but to the user it looks like there was an error because it can’t post the success message. Can you point me in the right direction here, I have tried everything I can think of. Thank you!

    • Nate Smith 01:09 PM 27/4/2012

      Google “headers already sent php”, that should get you started in the right direction. Usually this problem is because you have extra whitespace somewhere. Hope that helps.

      • Mandy 04:43 PM 27/4/2012

        Ya, that is what I’ve been doing. I was just hoping you might have come across this before. It’s super frustrating. All I can find is about extra white space. Is there anything else that might cause it. I thought it was strange that it points to line one of validate.class.php, that’s the first place I checked and there is no extra white space. So I searched both docs and can’t seem to come up with anything. Thanks for your reply, let me know if you can suggest anything else :)

  • Elvis Ron 06:00 PM 05/5/2012

    Thanks so much Nate. You code actually saved me hours. It works perfectly and its awesome. I have two issues I would need help on.
    1. Is it possible to redirect to a thank you page I have already created?
    2. I’m not a PHP coder, but looking through the codes I found out that the code below can be changed to fit a custom error message like “Please enter a valid name” with the name of a variable appearing first. But I don’t know how.

    $this->setError($postName, ucfirst($postName).” must be at least {$min} characters long.”);

    Thanks and keep the good work.

  • sabrina 01:33 AM 09/5/2012

    I love your code. Everything works fine if there are errors but if their aren’t any errors i keep getting some undefined indexe notices and it points to the line that has the getError function. Any help in correcting this would be greatly appreciated. Thanks in advance

  • tom 08:33 PM 15/5/2012

    Just worked through your tutorial and got this working great!! Thanks very much for a clear concise tutorial explaining things in excellent details!!

  • Oladiran 03:42 PM 16/5/2012

    At first I didn’t get the tutorial but after carefully going thru and happy I got it. Tanks a lot for this great stuff. Please can u also drop a tutorial on how to set a perfect blog and embed it into your website. Love to hear from you soonest

  • Deepali 06:47 AM 08/6/2012

    hi Nate,
    I got this following errors..
    Notice: Undefined variable: name in C:\wamp\www\suyash_construction\enquiry_form.php on line 162 Call Stack #TimeMemoryFunctionLocation 10.0006705056{main}( )..\enquiry_form.php:0 ” />

    Notice: Undefined variable: email in C:\wamp\www\suyash_construction\enquiry_form.php on line 166 Call Stack #TimeMemoryFunctionLocation 10.0006705056{main}( )..\enquiry_form.php:0 ” />

    plzz help out..

    value=”" /> …It is wrong??

    plzz rply

  • Pat 05:12 PM 11/6/2012

    Great tutorial…. something that I have been looking for for some time as I use an ancient form that presents the errors on another page requiring the use of a Go Back button. I have tried this code on the server but I get a 500 error and I am thus stuck at the first hurdle. I do not mind fiddling with PHP but I am not very skilled. Any pointers that might get me beyond hurdle.

  • Dan 01:58 PM 17/6/2012

    Love this form, but I am stuck. Obviously, you need to change the email address to reflect your own. What other parts of this form need to be changed – i am clearly not doing something right because the form doesn’t even return any errors when blank – it just returns me to my home page. No email is sent either.

  • Pat Flynn 09:32 AM 27/6/2012

    Hi Nat, I love this tutorial and the tidy code. My old form validates by bringing the visitor to another page and back to make corrections. I was hoping to upgrade to a form presenting the errors on page and your code is ideal as it presents a great result. I have worked up the code as presented at the link above and I get the mail sent through fine. However when it should present the message “Your message has been sent” it is going to an Oops Page! Page not found. I have been around the houses on this and although I think that the following line might have something to do with it I have been unable to get it resolved.

    $url = “http”. ((!empty($_SERVER['HTTPS'])) ? “s” : “”) . “://”.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
            header(‘Location: ‘.$url.”?sent=yes”);

    Have you came across this before and could you give me a pointer to finding the way out ?
    Thanks in advance.

    • Nate Smith 02:06 PM 27/6/2012

      You should just be able to comment out the $url variable like so: //$url = “http”. ((!empty($_SERVER['HTTPS'])) ? “s” : “”) . “://”.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

      and then just hardcode in your url here:

      header(‘Location: ‘.”http://www.mysite.com/contact/?sent=yes”);

      So just change “http://www.mysite.com/contact/” to your contact forms url. It’s not ideal, but it should get it working for you.

      • Pat Flynn 10:37 PM 27/6/2012

        Thanks for getting back. I did the comment out and hardcoded the header as you said pointing to the contact.php
        Result = On click Send it returns a unstyled form page….yes all white without any of the css on board ! This must be a step forward from where we were with the Oops Page not found scenario, that we had earlier. Why might it not be connecting with the style sheet ?

      • Sean 10:18 AM 05/11/2012

        Hey – great tut. I was looking at the comments, and I did notice one thing that can be done to clear up some of the confusion regarding the redirect.. Its imperative that you place the quotes around the redirect page and its extension like this: header(‘Location:’.”thanks.html”.”?sent=yes”);

        Also make sure that the literal form url isn’t in the “Action” tag, otherwise the redirect will duplicate in the URL and it’ll be 404 all.. night long,… all night.. …all night long…

        Great form though, I hope to see more.. Thanks!!

  • rob 01:39 PM 28/6/2012
  • Pat Flynn 08:58 AM 29/6/2012

    Thank You. Had to move the styling back into the contact.php and that sorted it. Again thanks for your help and for sharing the code.

  • Mike 04:20 PM 15/7/2012

    This form is mostly working, however the redirect that appends ?sent=yes is not working. I can send an email to the specified email address. The redirect does work, as I am sent to the same page the form is on, however the sent variable is not appended.

    //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”);

  • Mike 04:58 PM 15/7/2012

    I figured out my problem. I had created a second PHP for testing called index2.php, and the redirect was going to the original index.php which still existed on the server.

  • goran 10:01 PM 25/7/2012

    Thank You, works perfect

  • Sean 08:01 PM 10/8/2012

    Hey – the code runs great! easy to add menus and other string vars, I did wonder how I can get the form to disappear upon successful send. So that the “Thank you your message has been sent is the only thing showing, not the now empty form below it. Thanks in advance…

  • Marty 08:19 AM 11/8/2012

    Hi Nate,

    Firstly great script, really well explained. But im having some troubles. I have got the form to work, but im having some issues with the error messages. How do you modify the code for each error message. Think im probably missing the obvious.

    This code is giving me the problem:
    private function setError($element, $message) {
    $this->errors[$name] = “please enter a name”;
    }

    public function getError($name) {
    if($this->errors[$name]) {
    return $this->errors[$name];
    } else {
    return false;
    }
    }// end getError

    If you could help it would be much appreciated.

    Marty

  • Mohan 07:17 AM 19/8/2012

    Hi a newbie here.. tried your good work but i cant get it right.. this is what i get, please help.

    Notice: Undefined variable: message_text in E:\xampp\htdocs\PHP Test\contact.php on line 116

    Notice: Undefined variable: errors in E:\xampp\htdocs\PHP Test\contact.php on line 117
    Name:

    Notice: Undefined variable: nameErr in E:\xampp\htdocs\PHP Test\contact.php on line 122

    Email:

    Notice: Undefined variable: emailErr in E:\xampp\htdocs\PHP Test\contact.php on line 126

    Message:

    Notice: Undefined variable: messageErr in E:\xampp\htdocs\PHP Test\contact.php on line 130

    • Ronnie Petty 03:34 PM 20/3/2013

      It’s because your using XAMPP and it’s your testing server running over localhost. Your issue is that you’re running up against this line of code here that is not calling to localhost.

      //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”);

      You could switch out HTTPS with LOCALHOST or you could just upload to a remote server and test it there.

  • Sam 12:54 PM 27/8/2012

    Hi.. thx for your code. I’ve followed all the instructions but still when I am doing the testing on server side I am still not receiving any emails.. but I am not getting any errors though.. after submission it’s taking me to the index page.. can I get some help please??

    Thanx a lot ppl

    Sam

    • Dani 06:56 AM 20/9/2013

      I get this same behavior. I tried cutting pasting the code, changing my email address and all different methods of paths to my include folder, and I still can’t get the form to load.

  • Marcin K. 09:30 PM 28/8/2012

    I would like to thank you so much for making this available. This is the only form I found, that was “php noob-enough” friendly. Everything is working like a dream! :) I had some trouble at the beginning, but that’s due to my ignorance (Thought copy and paste is enough, but reading through the comments sorted out all of my “issues” :P)

    I have also got one question: When the entered e-mail address contains a hyphen in the domain name, the e-mail form will give out an error. I have just discovered that by accident, when testing the form. I understand, that not many e-mail services have “-” in their domain name, however this will come useful to me. I have been unable to fix this myself in fear of destroying the validation.class.php. Would be very grateful, if you can help me change the settings of the validation file.

    Thank you so much again! This is an incentive to finally learn PHP.

    • Marcin K. 09:59 PM 28/8/2012

      Also, just one last thing. Is there a way I could ‘hide’ :

      Your message has been sent successfully!Please allow up to 24 hours for a reply. Thank you.

      What I mean is that, this leaves quite a large space, between the “Contact Form” title and the itself, when the form has not been submitted yet. I guess, if you access the website, you will know what I mean. Thank you and sorry to be a pain.

      • Marcin K. 11:11 PM 28/8/2012

        Sorry, just to clear everything – I fixed my other problem already, it was a ‘margin’ that I had to change and it fixed it, plus, re-reading my previous post – it completely doesn’t make sense, just ignore it :P

        The problem with the hyphen still remains if you would be able to find a minute :)

  • James 11:07 AM 06/9/2012

    Im haven problems with the script everything seems to works but I dont get the email though??

  • aimeedanger 09:17 PM 09/9/2012

    My form doesn’t seem to run the validation at all.
    http://www.crsmithconsulting.com/contact.php
    I can submit the form totally blank. Any reason why? I tried walking through your tutorial, then I just cut and pasted your final code with same results both times.

    • aimeedanger 09:21 PM 09/9/2012

      Never mind. I found the issue! In some situations, you need to change “.” in form action to “./contact.php”.

  • mikibrown 01:22 PM 18/9/2012

    Hy,
    thanks 4
    ur work.
    How I write a program that will send a form content to another page when click on submit button,
    using php

  • emj 10:12 PM 20/11/2012

    This works, but once I submit the form, I end up at the top of the page and have to scroll all the way down to the bottom to see whether the form was submitted or not (my form is at the bottom of the page). Do you have a solution for this?

  • megadr01d 10:40 PM 22/3/2013

    Best script/tutorial I found, Nate. Thanks a lot. It’s advanced yet easy to understand and it doesn’t use js alerts or new pages for error messages. 5 stars.

    • megadr01d 10:41 PM 22/3/2013

      Forgot to add, the CSS is pretty simple and doesn’t use too many crazy classes making it easy to adapt to anyone’s layout. Cheers.

      • megadr01d 10:45 PM 22/3/2013

        Too quick on the click. A good future tutorial would be a commenting system like this, preferably with sqlite or no db at all (my ideal would be for comments to be saved as plain text/markdown files so it’s easy to maintain).

  • sarah 03:35 PM 05/4/2013

    Hello Please HELP!!

    My website is running of XAMPP and I am trying to run the contact form but i just keep getting an error which is called ERROR 404??

    can anyone suggest any solutions to this???

  • duh 10:21 AM 06/4/2013

    I use a simpler form of this until now, that looks much better, I have a few questions:
    -first, is it possible to add a simple captcha code and how?
    -secondly, how to get back to the exact position of the form after clicking the submit button, and an error occurs? this is because the form is in the middle of a web page, now always return on top of a page!
    sorry for my bad english
    best regards

  • Daniel Rowley 03:14 PM 23/4/2013

    I am trying to CAPTCHA to the validation page, but am V new to php, any good examples you can offer would be greatly appreciated.

  • Kris 04:06 PM 29/4/2013

    When form is submitted I get a blank page with 1 character in the upper left “0″.?? Any idea’s what the issue may be?
    Thanks,

  • shevesh 04:19 AM 05/8/2013

    my hosting service is windows based and it say mail() allowed only on Linux platform. What I do now to send mails from here ..
    Any help would be much appreciated…

    Thanks

    • Nate Smith 01:29 PM 05/8/2013

      Ditch Windows and get a linux box! I’m not really sure about Windows hosting, you’d have to google how it or ask your host.

  • alex 08:04 PM 14/8/2013

    hi everyone!

    first of all. big up and many thanks for sharing and explaining that one! I really think i understand php a little bit better now and the form is really usfull for my project aswell. THX!
    I have a question and maybe someone of you could help me out with that…

    im wondering weather it is maybe possible to make the error messages vanish after some seconds, after they popped up!? Like: <> shows up when i push the “send” button without entering my name…and than make it hide again after lets say 5 seconds.

    I hope you got my thoughts.

    (pls excuse my language…im not a native speaker)

    cheers
    alex

About

Box Model Junkie is a site addicted to Front-end / UI development. We focus on tutorial relating to JavaScript frameworks, CSS3 and HTML5.