Creating a simple contact form with PHP

Creating a simple contact form with PHP

In this tutorial I will show you how to create a simple contact form with PHP. With the help of a contact form your visitors will fill out a form and its content will be send to you via email.


Step 1.
First of all let’s try to find out what we need in this project. We want that a visitor can send us a message but we don’t want to show our real email address to avoid any spam. We need all the information from the visitor to be able to send a replay to him which means generally a valid email address. To make our work easier we can introduce a subject field just to know what the message is all about. Besides this it would be fine if we could address our replay with the name of the visitor.

So the summary of the important user inputs:

  • Subject
  • Message
  • Name
  • Email

Besides this the main functional area – what we should implement - are the followings:
  • Creating a HTML form
  • Displaying error messages on the form if necessary
  • Validating user input
  • Sending the message via email
  • Display a thank you message if everything was success.
In the next step we begin with some coding.


Step 2.

Let’s make some coding as well. As we discussed before the form contains 4 inputs. Three of them are normal text fields for the subject, name and email and we have a text area for the message itself. Besides this we extend the form to be able to display any error message (see later) and to remember the visitor’s entries (see later as well).

As result our form will looks like this:

      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <table>
          <tr><td>Subject:</td><td><?php echo $error1; ?></td></tr>
          <tr><td colspan="2"><input type="text" name="subject" value="<?php echo $subject; ?>"></td></tr>
          <tr><td>Name: </td><td><?php echo $error1; ?></td></tr>
          <tr><td colspan="2"><input type="text" name="name" value="<?php echo $name; ?>"></td></tr>
          <tr><td>Email:</td><td><?php echo $error2; ?></td></tr>
          <tr><td colspan="2"><input type="text" name="email" value="<?php echo $email; ?>"></td></tr>
          <tr><td>Message:</td><td><?php echo $error3; ?></td></tr>
          <tr><td colspan="2"><textarea cols="40" rows="6" name="message"><?php echo $message; ?></textarea></td></tr>
          <tr><td colspan="2"><br/><input type="submit" name="submitBtn" value="Send"></td></tr>
        </table>
      </form>


We want to show the form only until it is not filled correctly. If everything is ok than we will display a Thank you message instead of the form. To realize this we will put the form code into a PHP function and call it only if needed. As parameter we will provide field values and error messages if necessary.

The function looks definition like this:


<?php
function createForm($subject="",$name="",$email="",$message="",$error1="",$error2="",$error3="")
?>



Step 3.
As next step we will implement the main HTML code. Here we first check whether the form was submitted or not. If the form was not submitted than call the above created function to display the form. If the form was submitted than store the values from the $_POST variable and make some validation with it (see details later). If any error occurs than we will display the form again but in this time we will prepare the form with the submitted values and error message(s). With this we can help our visitor to find the problem and solve it without type everything again.


In case of validation was success than we will send the mail (see details later) and display the Thank you message.

As result the main HTML code is the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
<?php if (!isset($_POST['submitBtn']))  {
    
createForm();
} else  {
      
$subject = isset($_POST['subject']) ? $_POST['subject'] : "";
      
$name    = isset($_POST['name'])    ? $_POST['name'] : "";
      
$email   = isset($_POST['email'])   ? $_POST['email'] : "";
      
$message = isset($_POST['message']) ? $_POST['message'] : "";

      
$error  = false;
      
$error1 = '';
      
$error2 = '';
      
$error3 = '';

      if (
strlen($name)<2) {
          
$error = true;
          
$error1 = errorName;
      }
      if (!
isValidEmail($email)) {
          
$error = true;
          
$error2 = errorEmail;
      }
      if (
strlen($message)<10) {
          
$error = true;
          
$error3 = errorMsg;
      }

      if (
$error){
         
createForm($subject,$name,$email,$message,$error1,$error2,$error3);
      }
      else {
          
sendMail($name,$email,$message,$subject);
    
?>

        <table width="100%">
          <tr><td>
            Thanks for your message!
          </td></tr>
        </table>
<?php
    
}
}
?>
</body>


[newpage=Page 2]

Step 4.
As I mentioned earlier we make soma input validation. Validating the name and message is quite simple here. We just check that these strings are long enough to avoid meaningless messages. Of course you can set the length as you want. Besides this we check the validity of the email address as well. To do this we will create a new function where we use some regular expression to check email.

The email checker functions looks like this:


<?php
// This function validates an email address
function isValidEmail($email){
   
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
     
   if (
eregi($pattern, $email)){
      return 
true;
   }
   else {
      return 
false;
   }   
}
?>



Step 5.
The last function we need to implement is one of the most important. This function is responsible for composing the email from the visitor input and sending it to the site owner. The function creates the email subject, header, the From field and the content itself. After this it will send the email. To avoid any problem with the html content we will use the PHP built in function htmlspecialchars to convert special characters to HTML entities.


The mail sender function looks like this:

<?php
// This function sends an email to the given address
function sendMail($name,$email,$message,$subject){
    
    
$subject = "Message from website: $subject";
    
$from    = "From: $name <$email>\r\nReply-To: $email\r\n"; 
    
$header  = "MIME-Version: 1.0\r\n"."Content-type: text/html; charset=iso-8859-1\r\n";
    
$content = htmlspecialchars($message);
    
    
$content = wordwrap($content,70);
    @
mail(MAIL_TARGET,$subject,$content,$from.$header);

}
?>


Step 6.
To make it easier to maintain the code we used some defines for error messages. So you just need to edit the first lines of the code if you want to change any message.
Beside this the target email address was defined here as well.

The complete contact form code is the following:


<?php

// Define your email address - where to send messages - here
define("MAIL_TARGET","youremail@domain.com");

// Here you can redefine error messages
define("errorName","Invalid name! It must be at least 2 characters long");
define("errorEmail","Invalid email address!");
define("errorMsg","Invalid message! It must be at least 10 characters long");

function 
createForm($subject="",$name="",$email="",$message="",$error1="",$error2="",$error3=""){
?>
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <table>
          <tr><td>Subject:</td><td></td></tr>
          <tr><td colspan="2"><input type="text" name="subject" value="<?php echo $subject; ?>"></td></tr>
          <tr><td>Name: </td><td><?php echo $error1; ?></td></tr>
          <tr><td colspan="2"><input type="text" name="name" value="<?php echo $name; ?>"></td></tr>
          <tr><td>Email:</td><td><?php echo $error2; ?></td></tr>
          <tr><td colspan="2"><input type="text" name="email" value="<?php echo $email; ?>"></td></tr>
          <tr><td>Message:</td><td><?php echo $error3; ?></td></tr>
          <tr><td colspan="2"><textarea cols="40" rows="6" name="message"><?php echo $message; ?></textarea></td></tr>
          <tr><td colspan="2"><br/><input type="submit" name="submitBtn" value="Send"></td></tr>
        </table>
      </form>
<?php
}

// This function validates an email address
function isValidEmail($email){
   
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
     
   if (
eregi($pattern, $email)){
      return 
true;
   }
   else {
      return 
false;
   }   
}

// This function sends an email to the given address
function sendMail($name,$email,$message,$subject){
    
    
$subject = "Message from website: $subject";
    
$from    = "From: $name <$email>\r\nReply-To: $email\r\n"; 
    
$header  = "MIME-Version: 1.0\r\n"."Content-type: text/html; charset=iso-8859-1\r\n";
    
$content = htmlspecialchars($message);
    
    
$content = wordwrap($content,70);
    @
mail(MAIL_TARGET,$subject,$content,$from.$header);

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
<?php if (!isset($_POST['submitBtn']))  {
    
createForm();
} else  {
      
$subject = isset($_POST['subject']) ? $_POST['subject'] : "";
      
$name    = isset($_POST['name'])    ? $_POST['name'] : "";
      
$email   = isset($_POST['email'])   ? $_POST['email'] : "";
      
$message = isset($_POST['message']) ? $_POST['message'] : "";

      
$error  = false;
      
$error1 = '';
      
$error2 = '';
      
$error3 = '';

      if (
strlen($name)<2) {
          
$error = true;
          
$error1 = errorName;
      }
      if (!
isValidEmail($email)) {
          
$error = true;
          
$error2 = errorEmail;
      }
      if (
strlen($message)<10) {
          
$error = true;
          
$error3 = errorMsg;
      }

      if (
$error){
         
createForm($subject,$name,$email,$message,$error1,$error2,$error3);
      }
      else {
          
sendMail($name,$email,$message,$subject);
    
?>

        <table width="100%">
          <tr><td>
            Thanks for your message!
          </td></tr>
        </table>
<?php
    
}
}
?>
</body>


Download:
You can download a simple contact from as well.