September 19, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Using PHP with Forms

  • March 22, 2002
  • By Elizabeth Fulghum
  • Send Email »
  • More Articles »
Once you know the basics of PHP's syntax and structure, it is fairly easy to make the leap to writing full-fledged scripts.

Because working with forms is one the most common tasks in writing applications for the web, the first script we write will be a form processor. Though a fairly mundane application, it will introduce you to a range of important concepts, including how PHP handles variables that come from outside the running script.

First, let's take a quick look at the HTML end of forms, and go into a little bit of detail about how data is passed from forms to the server.


Form Basics

You have probably worked with HTML forms dozens of times, but have you ever really thought about how they work?

Take a look at the following:

<html>
<body>

<form action="page.php" method="post">
<input type="text" name="name" value="">
<input type="submit" name="submit" value="submit">
</form>

</body>
</html>



This is probably one of the simplest forms you could have in a page. It contains a text field called "name" and a submit button. Notice the method specified in the opening form tag.

As you might remember, there are two options for the method -- GET and POST -- which determine how information is passed from the form.

Without getting technical, here's the difference: GET sends the form information appended to the URL which is the same way that information is sent from a link. POST, on the other hand, sends the information transparently as part of the header of the page request.

Unlike GET, information sent via POST is not affected by any browser limitations on the length of URLs, and is not visible to the user. It is for this reason that POST is usually the chosen method for forms, unless you are debugging your script and need to see what is being passed to it. You will see why this distinction is also important to remember for the purposes of programming a little later on.


From the Form to PHP

Once a server receives information from a form posted to a PHP script, the programming takes over. This is where PHP really starts to shine. Every value passed from the form is automatically available to the script using the name given to the input in the form. For example, if you used the sample form above, and entered "Billy Joe Bob" for the name, then the name of that value in the script would be accessed as a variation of "name".

The version of PHP running and configuration of the php.ini file determines exactly what variation the value will be available by. These settings affect forms and data passed via links as well as predefined server and environment variables. Here are the possible situations:
  1. track_vars setting is on in the php.ini file: GET, and POST variables (among others) will be available through global arrays: $HTTP_POST_VARS and $HTTP_GET_VARS. For example: $HTTP_POST_VARS["name"]. Note: these arrays are not global.
  1. register_globals setting is on in the php.ini: GET and POST variables will be available in the format of standard variables. For example: $name. Variables passed from forms are automatically part of the global namespace.

  2. register_globals and track_vars are on in the php.ini: variables are available in both forms.

  3. PHP version 4.1.0 and higher: Due to security concerns, register_globals is being deprecated. Though still on in default configurations of 4.1.0, following releases will not have the setting enabled. New, shorter, arrays have been introduced to replace the old $HTTP_POST_* arrays: $_GET, $_POST. These arrays are also automatically global. For Example: $_POST['name']
For the remainder of this article, as well as this series, the newest $_* arrays will be used when handling variables from outside of PHP. If you are using an older version of PHP, you will need to replace the variables used in the sample scripts with the format that works under your particular configuration; however, its also advisable to upgrade to the newest version of PHP as soon as possible.


Writing a Form Mailer

Before you write any script, it is important to analyze what functions you need to perform and come up with a brief outline. For this script, there are a couple of things we want to include beyond simply sending the contents of the form:   - Display a form and allow the user to submit their name, email and a message. - Make sure all required fields are filled in. - Display a message and redisplay the form if required fields are missing. - Do some simple validation on the users email address. - Send the user's message via email - Display a thank you page.   Just like any other project, having a mental or written blueprint of what you want to do cuts down on the amount of changes because you forgot something and makes writing the script easier and faster.  

The Form

<html>
<body>

<br><br>
<?=$errormessage?>
<br>

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<table width="500" border="0" cellpadding="5" cellspacing="0">
<tr><td>Your name:</td><td><input type="text" name="name" value="<?=$_POST['name']?>"></td></tr>
<tr><td>Your email:</td><td><input type="text" name="email" value="<?=$_POST['email']?>"><td><tr>
<tr><td>Your message:</td><td><textarea name="message"><?=$_POST['message']?></textarea></td></tr></table>
<input type="hidden" name="required" value="name,email,message">
<input type="submit" name="submit" value="submit">

</body></html>



Save this as form.php and take a look at it. For the most part, this form is strictly HTML. There are 3 input fields: name, email and message that the user will fill out.

Since the scripting that handles the form input will be in the same file as the form itself, we use $_SERVER['PHP_SELF'], a server variable representing the file name of the script that is currently running, as the form action. Essentially, we are posting the form back to the current URL, whatever that may be.

<?=$errormessage?> does not output anything unless there is an error in the user input - in which case its replaced by the error message.  

Also notice that PHP is used to set a default value for each of these fields. If the user leaves one of the required fields blank, we will want to redisplay the form. To keep them from needing to re-type information, we use the values from the first time they submitted the form to pre-fill the fields.

The hidden field contains a comma delimited list of the field names we want to be required; it will be used to cycle through all of the values to check to see if they are filled in once the form is submitted.


The PHP

As mentioned before, the PHP to process the form will be in the same file as the HTML. This makes it easy to redisplay the form should there be an error in what the user submitted. So that the PHP is parsed immediately after the form is submitted, it should appear in the file before the HTML. If the form is validated, we will send the email and stop the execution of the script before the form is reached again. If there is a problem with what the user submitted, we will assign an error message to $errormessage and the form will automatically be displayed, since it comes after the PHP.

The first line of PHP needs to check to see whether or not the form has been submitted. The easiest way to do this is to see whether a value from the form is present or not. Since the value of the submit button is always passed with the form, it is idea to use for checking:

<?php
if ($_POST['submit']) {
   print "the form has been submitted";
}
?>



Add this code snippet before the html for the form in form.php, and run the file from your browser. When you fill out the form and press submit, you will see "the form has been submitted" at the top of your browser, followed by the form. Putting all the code to validate and send the contents of the form within this if statement will ensure it will only execute if the form has been submitted.

The next step is to check and make sure that all of the required fields are filled out. To do this, we need to grab the list of required fields from the hidden form field and split them into an array. Once they are in array form, we can loop through them checking to make sure the associated variables are not empty.

To split the list, we can use one of PHPs built in functions, explode(), which "explodes" a string on the occurrence of another string, and assigns the results to an array:

<?php
if ($_POST['submit']) {
   $required_fields = explode(",", $_POST['required']);



Now that we have an array that contains the required fields, we can loop through it. If a field does not have a value, we need to indicate that it's missing. The easiest way to do that is by incrementing a counter each time a variable is empty:  

   $error = 0;

  foreach($required_fields as $fieldname) {
     if ($_POST[$fieldname] == "") {
        $error++;
     }
  }



Here the execution of the script branches.

If $error is still equal to 0 after the end of the loop then we know that the user filled in all the fields and we can go on to do some simple validation of the email address:  

   if ($error == 0) {
      if (strstr($_POST['email'], "@") and strstr($_POST['email'], ".")) {



Using the built in PHP function, strstr(), this if statement simply checks to make sure there is a @ and period in the email address. Though you can perform more complex validation that checks for the proper syntax of email addresses, and even checks to make sure the entered domain name is valid, this will weed out the more creative fake addresses a user might enter.
If the email address contains both of these values, then we can send the users email. 

PHP includes a function to send email called mail(). It follows the following format: mail (TO, SUBJECT, MESSAGE (optionally:, additional headers, paremeters).

Optional additional headers includes information such as the From and Reply To addresses, any additional recipients and the content type (for sending email as plain text or html) to name a few. For this script, though, all we need are the basic parameters (remember to replace "youremail@your.com with your own email address):

         mail("youremail@your.com" , "Message from Web Form", $_POST['message'], "From: $_POST[name] <$_POST[email]>");



After sending the email, we need to display a message to the user letting them know that their email has been sent. Since they submitted their name, we can use it to personalize the message:

      print "<html><body>Thank you for submitting your comments $_POST[name]!</body></html>";
      exit;



Or even better, redirect them to another page:

         header("Location:http://yourdomain.com/thanks.php?name=$_POST[name]");
         exit;



Since we passed the name appended to the URL in the second sample, you could also use it in thanks.php in the form of $_GET['name'] (remember, variables passed via urls are available in the $_GET array). Including the exit statement after the print or header statement ends the execution of the script; it is used here so the form is not redisplayed.

Now that we have handled the part of the script that sends the email, we need to work more on the error handling. We bundled the code block for validating the email within an if statement checking to make sure all the fields, and the code block for sending the email within the if statement validating the email. To display a message if there are errors in the form, we need to work backwards logically.

First, the if statement for the email validation is closed, and an else statement is defined to display a message should the email not validate:  

      } else {
         $errormessage = "<b>The email address you entered does not appear to be valid<br></b>";
      }



Finally, the if statement for the field checking is closed and an else statement is added to specific what should happen if any fields are empty, the opening loop to see if the form was submitted is also closed:  

   } else {
      $errormessage = "<b>You have left some required fields in the form blank! Please fill in the form completely.";
   }
}
?>



Thats all there is to it. You can view the whole script here, or save your working file and test the form in your browser.

Finally

You can easily expand on this form for all different sorts of applications. Next time, we will explore how to work with files, and revisit forms to create scripts that store and update information on the server. Stay Tuned!

Things to Remember:

  • Forms can either be sent using the GET or POST methods. GET works the same way links work: data is sent by being appended to the URL. POST sends form data as part of the header request. This method is more secure since the user cannot see the information that's being passed and is not affected by any limitations browsers may have on the length of the URL
  • Name/value pairs passed to a PHP script via forms (or links) are automatically available.
  • Depending on the version of PHP and the configuration of the PHP.ini, the extact format of external variables (including those sent via forms and links as well as server and environmental variables) may differ.


Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been a fan ever since and frequently works as a freelance developer.

# # #






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel