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.
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.
HTML is not very difficult to learn, but it is a necessary skill since you will be editing pages manually using your text editor.
| 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 |
form.html where form is a filename of your choosing.form.html file.
'formresults.php'.data.dat.formresults.php, where formresults is a name of your choosing.formresults.php file.
form.html - read onlyformresults.php - execute onlydata.dat - write onlyUsing 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.
form.html for the remainder of this tutorial.If you would like information on how to create web forms in Microsoft FrontPage XP 2003, click here to visit our forms tutorial.
form.html to Use PHPform.html to be meaningful.formresults.phpWhen 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.
formresults.php for the remainder of this tutorial.The modified code should resemble the following:
<form name="form1" method="post" action="formresults.php">
...
</form>
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) |
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.
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).
formresults.phpJust 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 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:
a (append) - adds data to the specified target, starting at the end of the filer (read) - retrieves data from the specified target, starting from the beginning of the filew (write) - writes data to the specified target, starting at the beginning of the file and overwriting any previously-written informationWhen 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>
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
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
This file can be written to by anyone. Only the owner of the file (you) can read it. |
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.
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.
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: