newb.org.uk >> Tutorials >> Tutorial: Simple PHP Email Form

During my years of experience, a question that has often been posed to me was how to go about creating a simplistic and easy to comprehend contact or email form using HTML and PHP, which overall is a rather simple task. In this tutorial, I will attempt to outline and then explain in detail the development process required to create one.

  • Things you will require:
  • A web-server running PHP
  • A text editor ( I recommend Notepad++  )
  • Some previous HTML/XHTML knowledge
  • A smattering of PHP knowledge
  • About 15 minutes

The Beginning

The most basic of contact forms, which we will cover in this tutorial, mainly involve two parts that must be created; these being the HTML form itself, and the PHP engine that will then process the input from the HTML form and dispatch it to the appropriate email address in due course.

The first thing that needs to be created, therefore, is a simple HTML form that can serve as the user interface to our little writing engine. Remember, this is simply provided as a guide, and I'm sure many people out there will have better ways to layout contact forms. Create a new HTML document and input the following - or something else along similar lines.

<html>
  <head>
    <title>PHP Email Form</title>
    <style type="text/css">
      body,input,textarea{font:12px sans-serif;padding:0px;}
      b{min-width:120px;float:left;display:block;height:20px;line-height:20px;}
      input{margin-bottom:2px;width:120px;padding:4px;}
      textarea{width:240px;padding:4px;height:120px;}
    </style>
  </head>
  <body>
    <form action="mailer.php" method="POST">
      <b>Your Email:</b> <input type="text" name="email"><br>
      <b>Subject:</b> <input type="text" name="subject"><br>
      <textarea name="message">Message</textarea><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Note that the style declarations in the head section are optional, and were simply included here to make it look nice. Make sure the target="mailer.php" attribute in the form tag points towards the location of your soon-to-be engine file, and then we'll walk through the contents of this created HTML file. Provided you have basic knowledge of how HTML works, I would presume that you are aware how most of the above functions, especially the html, head, title, style and body tags that are used at the top of the file.

For those that don't, I will attempt to explain as quickly as possible. The HTML parsers in your web-browser work by reading the web-page file for various 'tags' that denote different elements. Each HTML document always starts with a <html> tag, which informs the parser that this is, indeed, a HTML document. The <head> tag then informs the parser that we have reached the header document of the page, which contains information about the page itself, such as stylesheets, meta-tags and of the course the page <title> tag. <body> then informs the parser that, finally, we have reached the actual web-page content itself.

Each HTML tag must be 'closed' after it is finished. For example, in the code provided you can see that after the contents after the <head> tag, there is a </head> tag which signifies the end of that section, and this is the same for most other elements such as <div>, <table> or <body>.

Based upon this explanation, it should be quite simple to work out how the rest of the web-page functions, however further information can be obtained at W3Schools whilst the site above can be viewed here.

The Mailer Engine

 Okay - now that we have the form we require to submit the email content, we have to create the mailing engine that actually sends the email. This, again, is a pretty simple process that only requires the most basic understanding of PHP. A brilliant resource for this is, of course, php.net, which contains information and resources related to every individual function and is always worth checking up on. I will first provide the source code required for this page to work, and will then explain it in some detail to ease understanding. There are also limited comments in the code itself to help you understand better if you read through.

The code we require for the engine itself, overall, is quite simple, and can be found below. This file should obviously be saved the same name as whatever you specified in the target attribute of the HTML contact form. Note that every line of PHP code must end with a semicolon ( ; ) or the processor will error.

<?php
  
// Take some variables from the form
  
$email    =  $_POST['email'];
  
$subject  =  $_POST['subject'];
  
$message  =  $_POST['message'];
  
  
// Set some other variables, for example who the email goes to
  
$target    =  " This e-mail address is being protected from spambots. You need JavaScript enabled to view it ";
  
$headers   =  "From: $email \r\n";
  
  
// Make sure our lines are no longer than 70 characters each
  
$message   =  wordwrap($message70);
  
  
// Send the mail and check response
  
$result    =  mail $target$subject$message$headers);
  
  if ( 
$result === TRUE ){
    
// Mail was sent, print a message
    
echo "<h2>Success!</h2>The email was sent to $target without error.";
  } else {
    
// An error occured, tell the user
    
echo "<h2>Error!</h2>Sorry, an unkown error has occured.";
  }
  
  
// Script is complete
?>

OK - now that that's into your head lets take a quick look through the code to explain what it actually does. I will be making reference to various pages on the php.net site, so it may help to have it open in a new window.

First of all, I should probably point out some standard notation that is used in pretty much every PHP page, and is therefore pretty useful to know. The start of a PHP document (or some PHP code within a HTML page) is signified by the identifier <?php, which informs the web-server that the following section is to be processed as PHP code before sent to the user, and the end of said section or page is signified with ?> - pretty simple, if you ask me. Comments in PHP source code are signified by either // for a one line comment, as in the code above, or by surrounding multiple lines with /* and */ to create a multiple line comment. Note that comments can be used to temporarily remove, or 'comment out' bits of code for debugging purposes.

Variables in PHP, unlike some other programming languages such as C++ do not have to have their type declared at any time - the code processor is clever enough to keep track of what type of content the variable contains.

  // Take some variables from the form
  
$email    =  $_POST['email'];
  
$subject  =  $_POST['subject'];
  
$message  =  $_POST['message'];
  
  
// Set some other variables, for example who the email goes to
  
$target    =  " This e-mail address is being protected from spambots. You need JavaScript enabled to view it ";
  
$headers   =  "From: $email \r\n";

This section of the code portrays how variables are assigned in PHP, and also how arrays are accessed. To assign a value to a variable, simply use the code $variable = "value"; and the variable will be created and have the value assigned to it. In this code, you can see I have used the notation $email = $_POST['email']; which portrays the use of arrays. When submitting a form via the POST or GET method (defined in the HTML form), the information is provided to PHP via the $_POST and $_GET arrays, respectively. For further information on variables, check out this page on php.net.

The next section is practically optional, and simply ensures that each line of the email does not exceed 70 characters in length in order to maintain compliance with the email standards. It simply calls the function wordwrap(); on each line of the message contents, and causes them to be 'wrapped' to 70 characters in length. Pretty obvious, eh?

  // Send the mail and check response
  
$result    =  mail $target$subject$message$headers)

This section of code will, probably by some people, be called 'the most important part,' as this is the single line of code that is responsible for sending the email itself. In laymans terms, the contents of the variables entered into the function are used by the processor to execute the function of the function, which in this case is to send an email! Note that you can also type values directly into the function ( provided they are surrounded by either " or ' ) instead of using variables. At this point, the return value of the mail(); function ( either TRUE or FALSE, depending on whether the mail succeeds or not ) is retrieved and stored in the $result variable, in order for a simple if() check to determine the status of the email.

Whilst this may look complex, in reality the if check is one of the simplest and most effective ways to accomplish dynamic error and value checking, and coupled with else allows for a great deal of flexibility.

  if ( $result === TRUE ){
    
// Mail was sent, print a message
    
echo "<h2>Success!</h2>The email was sent to $target without error.";
  } else {
    
// An error occured, tell the user
    
echo "<h2>Error!</h2>Sorry, an unkown error has occured.";
  }
  
  
// Script is complete
?>

In essence, the if function simply checks if the expression contained within ( and ) is matched, and if so, runs the code immediately following it. In order to run multiple lines of code after an if function, simply surround the whole of these lines with { and }, which will allow the block contained within it to be run as one. In this case, the expression being evaluated is a simple check of whether or not our mail(); function returned TRUE or not. If it did; the script then uses echo(); to output a simple success message, telling the user their mail has been sent.

However, the use of an else switch immediately after the code-block containing the error is automaticall ran if the condition of the if function is not met. Basically, it can be used to run commands whenever the if commands would not run - in this case, it is used to again output a message, this time informing the user that the mail sending failed for whatever reason. Further info on if and else.

Well, this completes the tutorial. I hope you have learned as much reading this tutorial as I forgot whilst writing it, and that whatever form you intend to create works quickly and effectively, even under heavy load. Watch this space for another tutorial, probably a bit better than this one, within the next week or two. For comments, criticism, donations or encouragement, please don't hesitate to contact me.

Written: 2009-08-16 00:24:43

Website programming, design and content copyright © 2010 Ellis Grouse, all rights reserved.
About - Contact - Links Back to Top

newb

Ellis
Age: 18
Location: Sunderland, England
Occupation: Layabout Student

Befriend: