Using Forms in Web Pages

The Internet started off as a one-way flow of information. You chose the web page you wanted to view, and the server provided it to you. It didn't take long before people started wanting to send information the other way, from the user to the site owner. The first response was simple forms, and they remain very useful.

This article will show you how to build a form using Dreamweaver, and then gather the information users put in. It is assumed that you already know how to create web pages using Dreamweaver (if you do not use Dreamweaver it should be easy to figure out how to do the same things in your favorite HTML editor). We will be using a programming language, PHP, but no programming experience is required, nor any real aptitude for programming. What we will not discuss are ways to deal with the information gathered. We will put it in a format that is convenient for reading it in to various applications, but their use is either fairly general knowledge (e.g. Excel), covered elsewhere (e.g. Stata or SAS), or well beyond the scope of this document (e.g. SQL).

Note that the example we'll do is designed to teach a variety of techniques and is probably more complex than you will need. What's more, most forms only require the simplest things we'll do. So if you find yourself confused by foreach loops and arrays, don't worry about it. Just find ways to make the tools that make sense to you do what needs to be done.

The Process

The process of using a form

Gathering information on the web using forms involves several steps. First, the user opens the web page containing the form, fills it out, and clicks a button (typically labeled Submit). Their browser then sends the information to the web server, with instructions to run a particular program using that information as input. This program must do something with the information--we will discuss displaying it in the user's browser, sending email, and saving it in a text file. It also creates the web page the user sees after clicking Submit.

Thus you will need to create two pages. The page with the form is just a standard HTML page, including the HTML code for the form elements (text boxes, buttons, etc.). The second is the program to handle the data. With PHP, this is simply a web page with some code embedded in it (which is one of the reasons we'll be using PHP as opposed to Perl, for example). The code will be run by the server before the page is sent to the browser.

As an example, suppose we are setting up a form that will allow users to request documents over the web (we'll also assume they are free--we're not doing e-commerce here!). We'll need to get the user's email address and the documents they want. We'll also ask them if they are affiliated with the University. This form will go in a file called request.htm. The program for processing the information will be called process.php. It will display the information in the user's browser as confirmation, send you an email, and save the information in a text file.

Creating the Form

Let's start by creating our page. Make a blank HTML page (or if you have a template for your site, use it) with the title and level one heading "Request a Document." Save it as request.htm.

The <form> Tag

The next thing we need to do is insert the form. Click Insert, Form. This will give you a red box. All the parts of the form will go inside this box. But the form itself tells the browser what to do when the user clicks submit. To set this behavior, click somewhere in the form (make sure the <form> tag is selected in the lower left corner of Dreamweaver) and open the Properties bar. You should see something like this:

Form Properties

The Form Name doesn't matter (unless you're planning to do some Javascript with it) but it might as well be something that makes sense, like request. The Method should be left as POST. The Action is the name of the program that will run when the form is submitted. We haven't written it yet, but type process.php in this box.

Form Objects

Now we'll start putting in the form objects. These are predefined "widgets" that all browsers know how to make. First, we'll put in a text field for the user to give their email address. Make sure the cursor is inside the form (the red box), type Email:, and click Insert, Form Objects, Text Field. This will create a text field with the default settings. Click on it, and we'll use the Properties bar to set it up how we want.

Text Box Properties

The name of this field does matter, because we will be using it in our program later. email is a good name. The Char Width sets (approximately) how many characters can be seen in the text field, and thus how wide it is. We'll use 40. If the user puts in something longer, the text will just scroll. Max Chars sets the maximum number of characters they can enter. Set it to 200--any email more than 200 characters long has to be a mistake anyway. Type should be left as Single Line, and Init Val (initial value) blank.

Our next object is a pair of radio buttons so the user can tell us whether they are affiliated with the University or not (why this is any business of ours is beyond me, but we need an excuse to use radio buttons). Radio buttons are named in memory of those old car radios where if you pushed in the button for one station, the button for the previous station automatically popped out. Thus radio buttons are used for situations where the user must choose one, and only one, option.

Type something along the lines of Are you affiliated with the University of Wisconsin? Yes No. We'll put buttons right before the words Yes and No. Put the cursor in front of Yes and click Insert, Form Objects, and Radio Button. Then put the cursor in front of No and do it again. Now we need to set the properties of the buttons using the Properties bar. Both need to have the Name set to affil (if the names are not exactly the same they won't interact). The one next to Yes should have Checked Value set to yes, the one, the one next to No should have Checked Value set to no. We'll make yes the default by setting its Initial State to Checked and no's Initial State to Unchecked.

Note that our form is looking ragged and just plain ugly. Generally it's a good idea to put forms in a table so everything lines up, but we'll assume you already know how to do that and not spend the time now.

Instead let's put in some documents they can request. We'll do this with a series of checkboxes. Users simply check the box next to the documents they want. Type Please check the documents you'd like:. Move to a new line, click Insert, Form Objects, Check Box, then type Document 1. Do the same same two more times, just changing the text to Document 2, then Document 3. In the Properties bar, set the name of all three boxes to doc[]. We could give them all different names, but this way our PHP program will be able to use all three as an array (more on this later). Set the Checked Value to doc1, doc2, and doc3 respectively, and all three should have an Initial State of Unchecked.

Just one more thing: a way to submit the form. Once again, click Insert, Form Objects, then Button. The defaults will work nicely for this one. Button Name, like Form Name, only matters for scripting, but Submit makes sense. Label is the text that appears inside the button, and Submit is perfect. Action should be set to Submit form. Reset form will reset all the fields to their initial values, allowing the user to start over. None sounds useless, but what it really means is that you want to write your own behavior for the button using Javascript.

Save this file, put it on the server, and take a look to test it. Do all the fields work? When you select one radio button does the other deselect automatically? If you hit Submit you'll get a message that process.php can't be found. That's because we haven't written it yet, and that's what we need to do now.

Writing the Program to Accept the Form

Now that we've got a form ready to send information, we need to have our program ready to receive it. PHP is a fairly simple programming language, something of a hybrid between Perl and Javascript, designed especially for web programming. It makes these kinds of forms relatively easy because much of the work is done for you. PHP will automatically read the information sent by the user's browser and create a variable for each field in the form. For example, since we made a field called email, PHP creates a variable called $email (all PHP variables start with a dollar sign) with the value set to whatever the user put in the field.

We're going to do three things when the user submits a request. First, we will reprint all the information they gave in their browser so they can confirm it. We will also have the server send us an email telling us that someone has made a request. Finally, we will write out the information to a text file on disk.

PHP Basics

PHP is inserted right into a standard web page, so let's start by making one. Open a blank page (or template) and save it as process.php. Make the title and level one heading Thank You for Your Request. Then in a standard paragraph type We received the following information, please look it over and confirm that it is correct. In the next paragraph type Email Address:, which we want to follow with the user's email address, as they gave it to us. But to do that we'll have to write some code.

To insert PHP code, switch to the code view (the button with the <> brackets). We're on our own now--we have to type rather than clicking buttons. Make sure the cursor is still in the right place--after the word Address: but before the closing tag of the paragraph ( </p>). To start a block of PHP code, the tag is <?php. Dreamweaver will be happier if you also put in the closing tag right away: ?> (especially if templates are involved). The code itself goes in between.

The print() Function

Much of the actual usefulness of PHP comes from using various prewritten functions. We'll start with print, which is what you use to put text in the web page. You could actually build the whole thing with print commands (which is what you always do in Perl), but we'll only use it when we have to. To tell the server to insert the users email address, simply type:

print($email);

Note that the semicolon (;) marks the end of one command and the beginning of the next one, if any. Just to check, your page should now have something like this:

<p>Email Address: <?php print($email); ?></p>

Let's try it out. Save your file and put it to the server. Then go to the form, fill it out and click submit. Your name should appear.

Controlling Your Program With if

Next we need to confirm whether they are affiliated with the University or not. PHP created a variable called $affil. If the Yes button was selected, then it will contain yes. If the No button was selected, it will contain no. We could do something similar to what we did with email and just print out yes or no. But we'll be slightly more ambitious.

We can use if to tell our program to do one thing if $affil is yes, and another thing if it is no. The syntax is

if(some condition)
{
do some stuff
}

If the condition is true, any commands inside the curly brackets will be executed. If not, they are skipped. So let's start with if($affil=="yes"). This will be true if the value of $affil is yes. Note that there are two equals signs (one equals is used for assignment--we'll get to that). If it's true, we'll have it print("<p>You are affiliated with the University of Wisconsin.</p>"). Note how we put the HTML code (the paragraph opening and closing tags) right inside the print statement. You could get around this by putting making a paragraph in Dreamweaver and then putting the code inside it--it's a question of how comfortable you are writing your own HTML. Now the logical next thing would be if($affil=="no") but we'll use a shortcut instead: else. It essentially means "if you didn't do the first stuff, do this instead." The corresponding print is print("<p>You are not affiliated with the University of Wisconsin.</p>"). So, to put it all together:

<?php
if($affil=="yes")
{
print("<p>You are affiliated with the University of Wisconsin.</p>");
}
else
{
print("<p>You are not affiliated with the University of Wisconsin.</p>");
}
?>

A couple of things to notice: one is that whenever we want to refer to an arbitrary string of characters, like "yes" or "<p>You are affiliated with the University of Wisconsin.</p>" we put the whole thing in double quotes. The second is the indentation. Everything inside the curly brackets is what's known as a block of code (ours have just one command, but they could have a lot more) and it's important to be able to identify the block so we know what is controlled by the if. When we indent the block, the structure is visually obvious.

Looping With foreach

Now we need to deal with the documents themselves. If we had given the checkboxes three separate names, we would have to deal with them individually. But since we gave them a single name with brackets following, PHP put them in an array. An array is just a list of values, which can be referred to by number. Thus the first document they requested can be referred to as doc[0], the second doc[1] (note how it starts with zero!), etc. Documents they did not request don't show up at all.

PHP gives us a very handy construct, the foreach loop, that allows us to take all the elements of an array and work with them one by one. The syntax is

foreach(array as variable)
{
do some stuff with variable
}

This defines a loop which will be run once for each element of the array. The first time through, the first element of the array will be placed in variable. Then second time through it will be the second element, etc. This allows us to write some code which will be executed for each element of the array (hence the name).

But what do we want to do? Nothing too complicated--just see which document they requested and list it. Recall that our form will send an abbreviation: doc1, doc2, doc3. We need to expand that to the full name (ok, for us that's just Document 1, etc., but you see the point). Let's put it all in an unordered list.

We want to put in some ordinary HTML, so put the cursor after the ?> tag, go back to the design view and type in You have requested the following document(s):. Then start an unordered list . We're going to make our loop create list items for that list. Go back to the code view, make sure the cursor is inside that list (between <ul> and </ul>, and if Dreamweaver put in an <li> </li> pair get rid of them), then type

<?php
foreach ($doc as $current)
{
if ($current=="doc1")
{
print("<li>Document 1</li>");
}
if ($current=="doc2")
{
print("<li>Document 2</li>");
}
if ($current=="doc3")
{
print("<li>Document 3</li>");
}
}
?>

Note how we now have two levels of structure (a loop and several ifs) so the indentation becomes even more important. In our loop, $current is the element of the $doc array we are currently working with. We then compare it with our list of codes (the short names we used in our form), and print the appropriate full title, along with the HTML that makes it a list item.

Sending Email

PHP makes it very easy for your program to send email--just use the mail function. This one is slightly more complex than print because it takes three arguments (the things in the parentheses). The first is the recipient's email address, the second is the subject, and the third is the body of the message. So let's suppose we want our program to send us an email when someone places an order, with their email address and the documents they requested. So for the recipient you will type your own email address, for the subject we want something generic like "Attention: Someone has requested a document" and in the body we want the email address of the person making the request and the list of documents. That will be the (slightly) tricky part.

We're going to need to build our message body in several steps, so we'll create a variable called $body to hold it. We'll start by assigning the easy stuff.

$body="$email has requested the following documents: ";

First note that the message includes the variable $email. PHP will automatically replace this with the value of $email. Also note the space at the end, for formatting. Next we need to add the list of documents. To do this, we will again need our foreach loop. The complete code will look something like this (put it right after the previous code, before the ?> closing tag):

$body="$email has requested the following documents: ";
foreach($doc as $current)
{
if ($current=="doc1")
{
$body.="Document 1";
}
if ($current=="doc2")
{
$body.="Document 2";
}
if ($current=="doc3")
{
$body.="Document 3";
}
if ($current==$doc[count($doc)-1])
{
$body.=".";
}
else
{
$body.=", ";
}
}
mail("rdimond@ssc.wisc.edu","Attention: Attention: Someone has requested a document.",$body);

The foreach loop and the first three ifs should look familiar. What's new is the stuff inside the loop. PHP uses a period (.) for concatenation, or adding one string to another. .= is a shorthand for "add the string on the right to the string on the left." So if the user requested a particular document, we add the name of that document to the body of our email message.

The last if and the else are a bit trickier, and also a something of a luxury, so if you end up confused don't worry about it. We're just trying to put commas between our documents and a period at the end of the list. I'll explain how it works from the inside out. The count function returns the number of elements in an array, so if the user requested all three documents, count($doc) will be 3. But since arrays start counting at zero, the last element in $doc is $doc[2], (the three documents they requested are stored as $doc[0], $doc[1], and $doc[2]). So we subtract one from the result of count and this gives us the number of the last document in our list. If the current document is equal to the last document, we add a period to our message body. If not, we add a comma and a space so it is ready for the next document in the list.

Once this loop is done, our message is ready to go and we send it with the mail function. One warning: when PHP sends a message it will come from a user called "nobody" with a full name of "unprivileged user." This is perfectly normal. PHP runs as part of the web server, and since the web server is one of the more vulnerable parts of the system it runs as "nobody" with no privileges at all.

Writing Data to a Text File

We're now ready for our last step: writing the data to a text file. To do this, we'll need to start with a touch of Linux. Log in to Linux and go to the directory where your web page is located. We need to create a file PHP can use to store the data it collects, and give it access to it. We can create an empty file using the touch command:

> touch requests

Now we need to give PHP permission to write to this file:

>setfacl -m u:nobody:rw requests

Now let's go back to Dreamweaver and put in the code to write to this file.

First we must open it using the fopen (file open) function. It takes two arguments: the name of the file, and a code saying what we want to do with it. We'll use a which means we will add to it. But fopen is slightly different from the other functions we've used in that it returns something, namely a file handle, which is how PHP knows what file to use. A returned value from functions acts a lot like a variable, except if we want to keep it, we need to assign an actual variable to it. We'll use (creatively enough) $file to store our new file handle. So the code looks like

$file=fopen("requests","a");

Next we must decide what we're going to put in this file. Let's assume we're going to eventually import this data into some other program (Excel, Access, Stata, SAS, SQL, etc.) so we want to put the data in a format it can read easily. Comma-delimited (a comma between each piece of information) is perfect. So we need to put all our variables together into a string, separated by commas. Here's the complete code:

$file=fopen("requests","a");
$text=$email;
if ($affil=="yes")
{
$text.=",yes";
}
else
{
$text.=",no";
}
foreach($doc as $current)
{
$text.=",".$current;
}
$text.="\n";
$tmp=fputs($file, $text);

We create a variable called $text and add pieces to it bit by bit. Note the heavy use of the concatenation operator again, including using it by itself (. as opposed to .=). Note also how we had to be careful where we put the commas. There's just one new item here: \n. PHP uses the backslash to indicated various special characters and codes. \n means go to a new line, so we have just one request per line.

When we're all ready, we use the fputs function to put the text into our file. It has two arguments: the file handle we want to write to, and the text we want to write. It also returns a variable that tells us whether it succeeded or not. We could then analyze that variable and generate error messages and such. But we're not going to worry about it--we'll save it in a variable because PHP needs us to, but we'll never use it.

And that should do it! Save everything, put it on the server and go test it. Fill out the form, view the results, check your email, and look at the requests file. Odds are it won't work the first time--welcome to the wonderful world of debugging. Try to figure out what part broke, and carefully compare what you wrote with the directions and the complete code listed at the end of this article. With some patience (and maybe some assistance from the Help Desk) it will work.

Using What You've Learned

You now have a fully functional form on the web--in fact it's probably an over-functional form. We made our form do a wide variety of things so we could use it as an example for learning a wide variety of things. Forms you create can probably be much simpler. In particular, there's probably no need to put the data in both an email and a file. You can probably even skip displaying it in the user's browser (after all, even if they made a mistake they can't fix it). In addition, most forms won't need to use an array and thus avoid all those foreach loops.

My hope is that you can take bits and pieces of what's in this article and make the forms you need work. Keep in mind you can contact the Help Desk for assistance. We can't write your code for you, but we can help you find mistakes or think through what needs to be done.

On the other hand, keep in mind that you are now programming. If you need to do something that isn't a straightforward modification of what is included here, you will need to spend a little time learning how programming works. PHP's web site is a great resource for doing so. It has tutorials for getting started, manuals for learning the language, and complete references for when you need to look up some detail. If you prefer paper, try Core PHP Programming by Leon Atkinson. It's a big book, but most of the bulk is references you'll rarely need. The first 115 pages provide a very good short introduction to programming, and will probably be enough to get you started. And then when you get stuck trying to get something to work, you can look it up in the immense reference section and find plenty of tricks for doing it.

The Complete Code

As a convenience, here is all the code used in this handout in one place, all set to be copied and pasted if needed:

<p>Email Address:
<?php print($email); ?>
</p>

<?php
if($affil=="yes")
{
print("<p>You are affiliated with the University of Wisconsin.</p>");
}
else
{
print("<p>You are not affiliated with the University of Wisconsin.</p>");
}
?>

<p>You have requested the following document(s):</p>
<ul>
<?php
foreach ($doc as $current)
{
if ($current=="doc1")
{
print("<li>Document 1</li>");
}
if ($current=="doc2")
{
print("<li>Document 2</li>");
}
if ($current=="doc3")
{
print("<li>Document 3</li>");
}
}

$body="$email has requested the following documents: ";
foreach($doc as $current)
{
if ($current=="doc1")
{
$body.="Document 1";
}
if ($current=="doc2")
{
$body.="Document 2";
}
if ($current=="doc3")
{
$body.="Document 3";
}
if ($current==$doc[count($doc)-1])
{
$body.=".";
}
else
{
$body.=", ";
}
}
mail("rdimond@ssc.wisc.edu","Attention: Someone has requested a document.",$body);

$file=fopen("requests","a");
$text=$email;
if ($affil=="yes")
{
$text.=",yes";
}
else
{
$text.=",no";
}
foreach($doc as $current)
{
$text.=",".$current;
}
$text.="\n";
$tmp=fputs($file, $text);
?>
</ul>

 

Last Revised: 8/26/2004