Abbey Workshop

PHP: Processing a PHP Form

This tip describes how to process a simple text form using PHP. To process a form, first you must make an HTML form. The code of an example form is also displayed below.

nameEmail.html

   1:<html>
   2:<head>
   3:    <title>Name and E-Mail Form</title>
   4:</head>
   5:<body>
   6:    <table border="1">
   7:    <tr><td>
   8:    <form name="Form1" method="POST" action="displaytext.php">
   9:        <p>Name: 
  10:          <input type="text" name="txtName" size="26" maxlength="25" />
  11:          <br />
  12:          EMail: 
  13:          <input type="text" name="txtEmail" size="26" maxlength="25" />
  14:          <br />
  15:          Message:<br/>
  16:          <textarea name="txtMessage" cols="65" rows="4"></textarea>
  17:          <br />
  18:          <input type="submit" name="Submit" value="Submit" />
  19:          <input type="reset" name="Submit2" value="Reset" />
  20:        </p>
  21:      </form>
  22:     </td></tr>
  23:     </table>
  24:</body>
  25:

The HTML tags define the field names, their sizes and their types. The form show how text fields are used.

As far the processing the form, the key tag to look at is the form element. There, the submission method is listed along with the program that will process the form. In this example, the form is going to be submitted using the POST method. This means the form data is sent inside the body of an HTTP request to the web server. If the method selected is GET, then the form data is sent as part of the URL sent to the web server.

The POST method is usally preferable as the data sent is not shown in the browser. Whereas, the GET method shows all the form data in the URL.

Next, take a look at the PHP file that will process the form.

displaytext.php

   1:<h3>Results</h3>
   2:<p>Here is the data you entered:</p>
   3:<p>Name: <? echo $_POST['txtName']; ?></p>
   4:<p>EMail: <? echo $_POST['txtEmail']; ?></p>
   5:<p>Message: <br>
   6:<pre>
   7:<? echo $_POST['txtMessage']; ?>
   8:</pre>
   9:</p>
  10:

All the form variables are stored in the $_POST array. By simply referring to each form field by name, it can be referenced in a PHP script. To try out this form and see the code in action, click here.