Form Handling with PHP

Lesson 2 - Simple Validation

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

In our previous example, we have hard coded the recipient e-mail address and have not tested to see if there is a subject, or body to actually send. Let's begin by doing a little validation. We'll assume that entries are required for all fields. We're also going to use the HTTP_REFERER to verify that the form was actually submitted from our site. Note that some browsers allow the user to block sending the HTTP_REFERER and some firewalls automatically block the HTTP_REFERER, so this not entirely reliable. We'll address that later in lesson 7:

   // initialize a variable to 
   // put any errors we encounter into an array
   $errors = array();
   // test to see if the form was actually 
   // posted from our form
   $page = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
   if (!ereg($page, $_SERVER['HTTP_REFERER']))
      $errors[] = "Invalid referer\n";
   // check to see if a name was entered
   if (!$_POST['Name'])
      // if not, add that error to our array
      $errors[] = "Name is required";
   // check to see if a subject was entered
   if (!$_POST['Subject'])
      // if not, add that error to our array
      $errors[] = "Subject is required";
   // check to see if a message was entered
   if (!$_POST['MsgBody'])
      // if not, add that error to our array
      $errors[] = "Message body is required";
   // if there are any errors, display them
   if (count($errors)>0){
      echo "<strong>ERROR:<br>\n";
      foreach($errors as $err)
        echo "$err<br>\n";
   } else {
      // no errors, so we build our message
      $recipient = 'user@example.com';
      $from = stripslashes($_POST['Name']);
      $subject = stripslashes($_POST['Subject']);
      $msg = "Message sent by $from\n
         ".stripslashes($_POST['MsgBody']);
      if (mail($recipient,$subject,$msg))
         echo "Thanks for your message!";
      else
         echo "An unknown error occurred.";
   }
   

Alright, now we have some basic validation. You can, of course, add more depending upon your needs and what you want submitted. You could, for example test the message body to ensure that it is at least some minimum length to prevent sending a single character, but what we have here will suffice for our present purposes.

Lesson 3