Curricular Support Home / Resources / Tips and Guides / PHP Tutorial / General Commands

Creating a Basic Form Handler Using PHP

This tutorial will teach you how to create a basic form handler using the PHP scripting language. No explicit knowledge of PHP is necessary, but it is helpful to know basic HTML as you will have to edit with tags (<HTML> is an example of a tag).

PHP is a scripting language capable of many things, including interfacing with some of the most common databases, sending an e-mail, encrypting data, transferring files, and even altering and creating almost any file type, such as images. PHP is a very powerful, expansive. Many books have been written about it, and if you wish to use PHP to create scripts that are beyond the scope of this tutorial, a good book may give you the information you need. However, in this lesson, we will not attempt the complex task of teaching the whole language; we will merely show you how you can collect data from a form (a survey, an exam, a sign-up sheet, etc.) and store it to a tab-delimited file that can be read in Microsoft Excel, SPSS, or most other spreadsheet programs.

Requirements

  1. A PC or Mac with a plain text editor (Notepad, SimpleText, etc., but not a word processor such as Microsoft Word) or a web page editor like Microsoft FrontPage or Macromedia Dreamweaver (preferably FrontPage for PC users, and Dreamweaver for Mac users)
  2. An account on a computer or server with PHP installed

You can set up your own computer as a server running PHP, but Virtual Union (VU) and Chet are two ITS-managed servers that have it pre-installed. All faculty may obtain an account on Chet by contacting ITS. All faculty, staff and alumni can create an account on VU.

  1. Experience with HTML and common HTML tags is required

HTML is not very difficult to learn, but it is a necessary skill since you will be editing pages manually using your text editor.

Files You Will Create

File File Type Program Required Example Programs
Form Webpage .html HTML or Text Editor FrontPage, Dreamweaver
Data Processor .php HTML or Text Editor FrontPage, Dreamweaver
Data File .dat Text Editor Notepad, SimpleText
Code Book Spreadsheet Editor Microsoft Excel

Project Outline

  1. Create a form using an HTML editor. Save the form as form.html where form is a filename of your choosing.
  2. Edit the form.html file.
    1. Change all the variable names and values in form.html to be meaningful.
    2. Change the action of the form to be 'formresults.php'.
  3. Create a "codebook" in a spreadsheet edtior. This is for your reference only.
  4. Create a tab-separated file with each variable name separated by a tab, finishing with a return. Save the file as data.dat.
  5. Create another web page with a feedback message. Save this page as formresults.php, where formresults is a name of your choosing.
  6. Edit the formresults.php file.
    1. Add the "collect-to-file" script, and customize it for your form.
    2. Add dynamic content.
  7. Upload the three files to your server. Adjust the file permissions as follows:
    1. form.html - read only
    2. formresults.php - execute only
    3. data.dat - write only
  8. Test your finished form multiple times to make sure it works properly.
  9. Collect all the necessary data.
  10. Opening the file in a spreadsheet program to view the collected data.
  11. Update the project for future use.

Step 1: Create a Form

Using your text or web page editor, create a web form. The web form should contain all the questions you wish to ask, as well as all the necessary input options, including:

Note: Multi-line Text Boxes are not recommended for this project. They allow users to add a line return, which is how we will be separating our data in the data file.

Verify that all of the form elements are surrounded by a <form> tag. When you are done, save your file as form.html where form is a name of your choosing.

If you would like information on how to create web forms in Microsoft FrontPage XP 2003, click here to visit our forms tutorial.

Step 2: Edit form.html to Use PHP

  1. Change all the variable names and values in form.html to be meaningful.
  2. Change the action of the form to formresults.php

When you create a form, most web editors will assign arbitrary names to each element. The problem here is that when PHP (i.e. the form.php file) receives the variables and values from the form, it uses the name specified in the HTML file as the variable name. As a result, instead of seeing an easy-to-understand variable name such as lastname, you will see a variable name such as textfield3. This is acceptable at first, but once you have collected pieces of data from multiple elements, it will be hard to decipher what it all means. Therefore, it is important to go back through all your code and change the form element names accordingly.

There are two ways of doing this: change it using the editor, or edit the actual HTML code. Some editors have options windows that can be accessed by right-clicking on the form element you wish to edit. From there, you can change how that element behaves or looks, such as its size, its name, etc.

If you choose to alter the code manually, the code for a radio button will look like this:

<p><b>Please Choose Your Gender</b>
<input type="radio" name="radiobutton" value="radiobutton" checked><br>
<input type="radio" name="radiobutton" value="radiobutton"> Male<br>
<input type="radio" name="radiobutton" value="radiobutton"> Female
</p>

This code will produce the following:

Please Choose Your Gender
Male
Female

Note: the extra radio button is to be used both as an instruction and as a way to collect missing data.

After you change the element names to be more descriptive, your code will resemble the following:

<p><b>Please Choose Your Gender</b>
<input type="radio" name="gender" value="0" checked><br>
<input type="radio" name="sex" value="M"> Male<br>
<input type="radio" name="sex" value="F"> Female
</p>

For a one-line text box, you will simply have to change the field name. The code, as it would be generated in an HTML editor, is shown below:

<p><b>Name: </b><br><input type="text" name="textfield"></p>

This code will produce the following:

Name:

After you change the element names to be more descriptive, your code will resemble the following:

<p><b>Name: </b><br><input type="text" name="name"></p>

For a pull-down list, it is recommended that you use your editor to change the settings. The code for a properly-configured pull-down menu would be generated as follows in an HTML editor:

<p><b>How do you feel today?</b>
<select name="select">
<option value="0" selected>Please Select One:</option>
<option value="5">Excellent</option>
<option value="4">Good</option>
<option value="3">OK</option>
<option value="2">Poor</option>
<option value="1">Horrible</option>
</select>
</p>

This code will produce the following:

How do you feel today? 

Note: Option 0 is to be used both as an instruction and to collect missing data.

Check boxes are similar to radio buttons. Each check box, however, is its own separate field. In each field, there will be one of two possible parameter values: "ON", which means the box is initially checked; or "", which means the box is initially unchecked. Just as with other form elements, the name= field must be changed to something more descriptive.

For example, look at the following code for a set of two check boxes:

<p>
<input type="checkbox" name="DVD" value="ON"> I own a DVD player.<br>
<input type="checkbox" name="VCR" value="ON"> I own a VCR.
</p>

This code will produce the following:

I own a DVD player.
I own a VCR.

Regardless of which form elements you decide to use, you will have to change the form action to use your PHP script. Initially, your form action code will look like this:

<form name="form1" method="post" action="">
...
</form>

To use your PHP script, type formresults.php as the value for action, where formresults is the name you have chosen for your data processor file. You have not made this page yet, but you should choose a name to use.

The modified code should resemble the following:

<form name="form1" method="post" action="formresults.php">
...
</form>

Step 3: Create a Code Book.

A codebook is for record keeping. It allows you to remember the meaning of each field and the names of each variable, as well as their meanings and possible values.

The following are examples of a few common variable types:

To make a codebook, look at the web page that contains your form. List all the names of the variables you have defined in the column of a table, and label the column HTML Variables. (As a reminder, the variable names are found in the name= section of the element tags.) Create a relevant title for each variable, a description of the variable's meaning, and a list or description of the possible values that the variable can take on.

The following table is an example of a codebook:

HTML Variable SPSS Variable Name Description Possible Values
pseudonym subjectID The subject's identifier A unique string between 1-20 characters
gender gender The subject's gender male, female
Q19 neuroticism The subject's neuroticism rating Integer between 1 (highly not neurotic) and 5 (highly neurotic)

Step 4: Create a Tab Separated File with Variable Names

Create a new file in your text editor that resembles the following:

subjectID      sex          neuroticism      Timestamp
|

This file should contain the SPSS variable names (which are more meaningful than the HTML variable names) that you chose for your codebook. Each variable corresponds to a column headings in your data table.

The variable names are each separated by a tab. After the last item in each row, you should insert a return. In other words, rows (participants) are separated by returns, and columns (variables) are separated by tabs.

Step 5: Creating a Feedback Message

The next web page you will create will contain a feedback message to the user that confirms that the form has been submitted successfully. When the user clicks [Submit], they will be transferred to this page and see a message like this:

Thank you for filling out our survey. Your data was successfully collected. Please close your browser window. Do not use your browser's [Back] button.

Use any HTML editor to create a new web page, and insert the feedback message as you see fit.

When you are finished, save the file as formresults.php (or whatever name you have assigned to your data processor).

Step 6: Add Code and Dynamic Content to formresults.php

  1. Add the "collect to file" script and customize it for your form
  2. Add any necessary dynamic content

Just as HTML code must be enclosed in the <HTML> and </HTML> tags, PHP code must be enclosed in the following braces:

<?php
...
?>

All PHP variables begin with a dollar sign ($). For example, the following are all valid variable declarations:

<?php
$age=21;
$name;
$happiness;
?>

All PHP statements must end with a semicolon (;), as shown above.

A double front-slash (//) or a pound sign (#) is used to put comments in your code. Comments are not executed by the PHP parser, nor are they displayed by the web browser. They are merely there for your personal reference. If a comment spans multiple lines, it is also possible to wrap it in the multi-line comment tags (/* and */).

To display text in a web browser, use the echo() command. Two strings may be concatenated by using the period (.) operator. The echo() command can be used to display HTML code as well as plain text.

For example, the code below demonstrates all of these operations:

<?php
$name = "Nick";
echo(5+6); // prints "11"
echo(<br>); // adds a line break
echo("My name is ".$name."."); // prints "My name is Nick."
?>

The echo() statement is a very versatile feature of PHP. Note that there are some characters - i.e. quotation marks ("), parentheses (()), dollar sign ($), etc. - that are used by PHP and may cause errors if included in a string. If you want one of these characters to be interpreted as text and not as a command, precede it with a back-slash (\) to "escape" it.

There are many different ways to achieve the same visible result, as shown in the following code:

<?php
// this is a comment

echo("My name is $name."); // you don't need to exit to print a variable
echo("My name is".$name.". "); // does the same thing
echo "My name is".$name.". "; // does the same thing
echo "My name is $name . "; // does the same thing

echo("You owe $ $money."); // this will produce an error
echo("You owe \$ $money."); // this will not produce an error
// use \$ when you want to print a "$".

/*
this
is
a
multi-line
comment
*/

# this is also a comment
?>

Use \n to insert a line-break into a string, or \t to insert a tab. Since you are using returns and tabs to separate the data you are collecting, these two characters are very important.

When PHP collects data from your form, it will store the data as a variable with the same name as the form element. For example, consider the following HTML code:

<input type="text" name="name">

The contents of the text box created with that code will be stored to a PHP variable called $name.

The Main Functions of the Form Handler Script

The fopen() function initializes file output.

$fileptr = fopen("file.dat","a");
// opens "file.dat" for appending
// sends the data pointer to $fileptr

In the above example, file.dat is the file to which the information in the form will be stored. Replace file.dat with the file name you have chosen for the data file. $fileptr is a variable that stores the current position in the file that you are opening. Every time you add something to the data file, $fileptr will "move forward" to a new empty position. The second parameter - a - is actually one of three possible options:

When creating a form handler, append is the best choice. If you choose write, the data from the previous user will be lost every time a new person fills out the form.

The fputs() function copies the contents of a string or variable into a file.

fputs($fileptr, $phpvar."\t");
// insert the contents of $phpvar appended with a tab
// into the file and position specified in $fileptr
fputs($fileptr, $lastvar."\n");
// insert the contents of $phpvar appended with a return
// into the file and position specified in $fileptr

In the above example, $fileptr is the file pointer that points to the position in the desired data file where the information will be added. Any variables, strings, or combinations thereof can be inserted using this function.

The fclose() function closes the file when it is no longer needed.

fclose($fileptr);
// closes the file referenced to by $fileptr

It is very important to use fclose() at the end of your script when the referenced file is no longer needed. Forgetting to do so may affect the performance of the web server you are using, and could cause future errors.

An example PHP script that makes use of all three functions is shown below:

<html>
<head>
<title>My Survey: Thank You</title>
</head>
<?php // update the textfile
$fileptr=fopen("file.dat","a"); // open the data file
fputs($fileptr, $firstName."\t"); // copy to the data file
fputs($fileptr, $lastName."\t");
fputs($fileptr, $email."\t");
fputs($fileptr, $Q10"\t");
fputs($fileptr, $sex"\t");
fputs($fileptr, $happiness."\n");
fclose($fileptr); // closes the file referenced by $fileptr
?>
<body>
<p>Your data has been successfully collected.</p>
</body>
</html>

Step 7: Upload Your File to a Server Running PHP

Unlike most HTML files, PHP scripts require special permissions to be set to work properly. Here is an example using the SSH File Transfer Client for Microsoft Windows. Macintosh userscan do the same thing using Fetch, which uses a similar interface.

Note: do not use WS_FTP to change the file permissions. Due to a bug in the program, changing the permissions of one file will change the permissions of every file in the folder. PC users should use SSH File Transfer Client, which is available for download on the Union College ITS website.

Form and Processor Pages

Form and Processor pages

This file can be read by anyone, and scripts within the files can be executed by anyone. Only the owner of the file (you) can alter them.

Data File

Data File

This file can be written to by anyone. Only the owner of the file (you) can read it.

Step 8: Testing and Debugging and Debugging

  1. Open your web browser, and navigate to the form page that you have just created.
  2. Enter arbitrary data into the form, and click the Submit button at the end of the form.
  3. The Data Processor page should load. Check the page for any error messages.
  4. If you have not received any error messages, download the data file, and view it using a text editor.

If you see an error message on any of the pages or files that you are trying to view, check to make sure you have not made any common mistakes.

After correcting any errors, upload the modified files to your web server again, and repeat the testing procedure.

Step 9: Collect Data

Advertise that you have a new form available in your classes, to your friends, on your home page, or elsewhere. Each time that someone fills out the form, their information will be added to the data file. You can come back and check the data file whenever you like.

Step 10: Opening the Data File in Excel or SPSS

  1. Using your FTP program, download the data file to your computer.
  2. Open Microsoft Excel or SPSS. Under the File menu, choose Open. In the Open window that appears, choose All Files (*.*) from the Files of type: drop-down menu.
  3. Navigate to the data file that you have downloaded, and click the Open button.
  4. A wizard will open that will allow you to convert your data file to a native format. Follow all instructions that appear on your screen, keeping in mind that the data file is a tab-separated.
  5. Once the wizard is closed, you will be able to use the data as an Excel or SPSS spreadsheet.

Step 11: Suggestions for Further Work

This tutorial is only a very limited look at the capabilities of PHP. If you would like to learn more about PHP's many features, there are a variety of books and websites available to help you teach yourself.

The following is a list of recommended books and resources:

There are many ways you can improve your form and make it easier for your users. The following are a few suggestions for the future development of your web form: