Form Processing with PHP

Lesson 1 - Getting Started

Index   Lesson << Prev 1 2 3 4 5 6 7 Next >>

We're going to start simple here. Note that it's wise to build in some precautions to prevent abuse by those who would use your server to send bulk unsolicited e-mail marketing messages (SPAM) and very likely get your site pulled. You may also want to build in some validation of the user's input. We'll cover those things in later lessons. First, we just want to illustrate sending a simple e-mail so that you learn the concepts involved.

TIP: Servers are configured to only parse files with specific file name extensions. Typically, a file with a .html or .htm file name extension are just served as is, without the server ever looking at the content. Specific servers may be configured to parse files with various extensions, but the most common is the .php file name extension. In order to get your PHP code to execute, the file must be parsed using the PHP processor. To make that happen, your files should be saved with the .php extension.

Sending an e-mail with PHP is as simple as:

   mail("[email protected]",
      "This is the message subject",
      "This is the message body");
	

That's pretty painless, isn't it? So how do you go about processing a form and sending the result to an e-mail recipient? Not much more difficult. Depending on whether you are using POST, or GET as the form's method, the values the user submits are available in the $_POST, or the $_GET arrays. For our tutorial, we'll be using the POST method. Let's examine a simple example. Assume you have the following form in your page:

   <form name="form1" method="post"
         action="<?php echo $_SERVER['PHP_SELF'] ?>">
      <table border="0" cellspacing="0" cellpadding="2">
         <tr>
            <td>Name:</td>
            <td><input type="text" name="Name"></td>
         </tr>
         <tr>
            <td>Subject</td>
            <td><input type="text" name="Subject"></td>
         </tr>
         <tr>
            <td>Message:</td>
            <td><textarea name="MsgBody"></textarea></td>
         </tr>
         <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="Submit"
               value="Submit"></td>
         </tr>
      </table>
   </form>
            

The astute among you may notice that the form is set to submit itself to the same page upon which the form resides. We'll get to that a little later.

So, to process that form and send the result via e-mail you can get the $_POST values and send it to the e-mail address [email protected] like this:

<?php
   $recipient = [email protected]';
   $subject = $_POST['Subject'];
   $from = stripslashes($_POST['Name']);
   $msg = "Message from: $from\n\n".stripslashes($_POST['MsgBody']);
   mail($recipient, $subject, $msg);
?>

WARNING: Okay, let me warn you that you will want some validation before trying to send the e-mail, so don't try to use this little example as your finished production form processor. While you may run this to test, do not leave it in a publicly accessible place after you are through testing it. We'll build on this in later lessons to give you ways to protect yourself.

Here's a complete example that you can run to test. Start a new document in Dreamweaver. Switch to Code View, select all and delete the existing code, then paste the following, or click here to download a copy of the page. Don't forget to replace "[email protected]" with the actual e-mail address where you want the message sent.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
	"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>Contact Form</title>
<meta http-equiv="Content-Type" 
   content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
   if ($_SERVER['REQUEST_METHOD'] != 'POST'){
      $me = $_SERVER['PHP_SELF'];
?>
   <form name="form1" method="post"
         action="<?php echo $me;?>">
      <table border="0" cellspacing="0" cellpadding="2">
         <tr>
            <td>Name:</td>
            <td><input type="text" name="Name"></td>
         </tr>
         <tr>
            <td>Subject</td>
            <td><input type="text" name="Subject"></td>
         </tr>
         <tr>
            <td valign="top">Message:</td>
            <td><textarea name="MsgBody"></textarea></td>
         </tr>
         <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="Submit"
               value="Send"></td>
         </tr>
      </table>
   </form>
<?php
   } else {
      error_reporting(0);
      $recipient = [email protected]';
      $subject = stripslashes($_POST['Subject']);
      $from = stripslashes($_POST['Name']);
      $msg = "Message from: $from\n\n".stripslashes($_POST['MsgBody']);
      if (mail($recipient, $subject, $msg))
         echo nl2br("<b>Message Sent:</b>
         To: $recipient
         Subject: $subject
         Message:
         $msg");
      else
         echo "Message failed to send";
}
?>
</body>
</html>
	

So what does this page do? Let's examine the code. The first thing we do is check the request method.

   if ($_SERVER['REQUEST_METHOD'] != 'POST'){
   

If the page is simply viewed in the browser, the request method will be GET. If the form has been submitted, the request method will be POST. So we first make a decision whether to display the form if the request method is not POST, or to process the form data if the request method is POST. The first time the page is viewed, the request method will be GET, so the next thing we do is obtain a reference to the current page that we can use in a ECHO or PRINT command. That reference is stored in the variable $me:

      $me = $_SERVER['PHP_SELF'];

Now, if the request method is not POST, we just exit PHP and let the form be displayed. The only PHP involved in that is where we assign the curren page as the form's ACTION attribute:

   <form name="form1" method="post"
         action="<?php echo $me;?>">
	

So now assume the user has completed the form and clicked the Submit button. What happens next? The form data is submitted as a POST to the current page. When that happens, the page is again called from the server, but this time the request method is POST. So our example skips displaying the form and goes down to the lines:

<?php
   } else {
   

Here, we invoke PHP again. It now begins processing the code in the ELSE block. The first thing we do is turn off error reporting because we want to handle that ourselves, although if you experience problems, you may want to comment this next line for debugging purposes.

      error_reporting(0);
   

Next, we assign the destination address, the message subject and the name and store them in variables:

      $recipient = [email protected]';
      $from = stripslashes($_POST['Name']);
      $subject = stripslashes($_POST['Subject']);
   

The first line hard codes the address where the e-mail will be sent. Obviously, you need to change that to the actual address where you want the message to be sent. The second line gets the user's name from the entry blank where the user typed it and the third line gets the subject that the user typed in the subject entry blank. Note that in the second and third lines, we apply the stripslashes() PHP function to the raw data passed from the form. The reason for this is, if the user entered quotation marks in their input, PHP (in most default configurations) will escape those quote marks using the backslash character. So, if the user typed their name as: John "Doc" Doe, it would be passed by PHP to your script as: John \"Doc\" Doe. The stripslashes() function removes the backslashes so you wind up with what the user actually typed. It is possible to turn off adding slashes, so we'll test that in later lessons. For here, we'll just assume that it's turned on.

Next, we build the message body to include the Name and the message we got from the form:

      $msg = "Message from: $from\n\n".stripslashes($_POST['MsgBody']);
   

Remember that we stored the user's name in the $from variable

Now that we have that, we simply call the PHP mail function. The mail function returns a value of TRUE if it succeeds, or FALSE if it fails, so we wrap it in an IF test so we can advise the user of the result:

      if (mail($recipient, $subject, $msg))
   

If the function succeeds and returns TRUE, we display a message to the user, using the PHP nl2br function to format the output:

         echo nl2br("<b>Message Sent:</b>
         To: $recipient
         Subject: $subject
         Message:
         $msg");
   

Otherwise, if the mail function fails, we show that result:

      else
         echo "Message failed to send";
}
   

That's all there is to it. In lesson 2, we'll start implementing some validation.

Lesson 2