Published on (
 See this if you're having trouble printing code examples

PHP Forms

Using PHP to Interpret Forms



• Experience the history of the web! This is a great resource; spend some time here.

• The University of Illinois at Urbana-Champaign -- The birthplace of Mosaic.

• HTML 2.0 Materials

• The home of PHP

• Good Introductory PHP Tutorial -- Forms are included.

• PHP Introduction from Developer's Shed

The Internet, as we know it today, is primarily the result of two seminal events:

  1. The February 1993 introduction of Mosaic, the first graphical Web browser (see references in the sidebar to the right), and,
  2. The 1994 addition of forms to the HTML specification.

Mosaic, with its multimedia capability, added entertainment value to what had previously been a bland character-based medium. Forms created the capability for dynamic Web sites tailored to user requests. Without either of these two developments, we would all probably be watching TV right now.

In view of the above, we'll start this column with a series on forms. Before getting down to the nitty-gritty, let's review our programming level assumptions and take a look at where we are going.

What I'm assuming

This column is not directed toward beginning programmers, although they are more than welcome to come along for the ride. I'm assuming our readers have a reasonable degree of programming experience. PHP experience is not assumed, but a background in a Unix-based language such as C or Perl would be very helpful. Whenever PHP deviates from typical programming conventions, I'll stop the show and take time to explain in detail. PHP arrays immediately come to mind.

Since embedded programming code segments in HTML documents is the main strength of PHP, it is also assumed you know HTML on a first name basis.

To get the most out of these sessions you will need access to PHP. Paraphrasing the old saying: "If your ISP doesn't offer PHP, move." If you need a low-cost PHP test bed, drop me a note at the address at the end of this article. PHP4 code is utilized in programming examples. I'll point out the differences between PHP3 and PHP4 when necessary. However, PHP4 has many advanced features and should be employed if at all possible. PHP is free, so there is little reason for your ISP not to upgrade.

Where we are going

The major goal of this series is to give you tools (program, function, or object) in each session that are immediately usable. When I do a series on a theme, as I'm about to do with forms, I'll build upon and expand on the material from previous sessions. My motto is "Start simply, and then dazzle them with my footwork!"

Add a little form to your life

When people start to get interested in Web-related programming, the first thing they typically want to do is a form. A form can be one simple input box on a search engine front end or a multi-page questionnaire.

The program form-one.php is the demonstration PHP program for our first exercise. Display the code here and cut and paste into your favorite editor, upload to your Web server, and run the script. If you have not uploaded PHP documents to your friendly ISP, check with your administrator to ascertain the extension required, typically php or php4.

Before going into code details, a few notes: PHP3 requires function declarations before they are called, so put the functions at the top of the script if you're trapped into PHP3. Also, the here document construct starting on line 44 is PHP4-specific so replace it with a multi-line echo statement.

PHP documentation calls the here document construct here print, but I prefer the Perl terminology since it's more descriptive. Notice I've used the here print construct to assign the big string to a variable, $HTML in this case. Some subsequent assignments are concatenated to $HTML and then printed. This minimizes I/O operations, which in turn increases program efficiency.

The here document construct is essentially a multiple line, double-quoted string. The new line character, \n, is automatically added to the end of every line. Perl programmers beware, there are three structural differences between the Perl and PHP versions of this construct.

The PHP version starts with three "<" characters, there is no semicolon termination after the starting label, and there is a semicolon after the terminating label. Anything that would normally appear between a double-quoted string may appear in this construct, including variables that will be expanded. The here document construct is a very convenient way of including a large group of HTML within a PHP block. Create a form with your favorite HTML editor and cut and paste it into a here document block as I've done in the example.

PHP variables

Variables in PHP are very much like their Perl counterpart, until we get to arrays. As with Perl, PHP variable names are case sensitive. All variables in PHP, including array references, begin with a $ prefix. Arrays in PHP are very interesting critters. Virtually all languages support the grouping of similar items into arrays indexed by a numeric value, typically starting with zero. Perl takes the concept an additional step with hashes, also called associative arrays, which are indexed by string values. Microsoft, in an effort to convince us they have made yet another invention, calls these same things collections. PHP does not distinguish between conventional arrays and hashes, and the same array can be indexed by either numeric or string values.

One of PHP's most endearing attributes is the ease of performing Internet-related functionality. To illustrate, the array $GLOBALS (as with Perl, case counts with variable names) contains environmental variables, cookies, data from forms, and user-defined variables. Lines 36 through 38 in the example program dump the contents of the $GLOBALS array. It's also a convenient way to dump a PHP array.

foreach ($GLOBALS as $Key=>$Value){
  echo "<LI>\$GLOBALS[\"$Key\"]=$Value\n";
} # End of foreach ($GLOBALS as $Key=>$Value)

Note that I always quote the top of the braces block in a comment at the end of the braces block. It may seem like overkill in a situation like this, but there is nothing more frustrating than trying to decipher someone else's program and encounter something like:


The $GLOBALS array contains a substantial amount of information that is available in your PHP program. The provided information will differ slightly from ISP to ISP, but do take some time to acquaint yourself with the information.

PHP makes a real effort to make our life easier. The individual components of the $GLOBALS array automatically spring into life. $HTTP_REFERER is the Perl equivalent of $ENV{"HTTP_REFERER"}. It gets even better. Take a look at the form fields starting on line 46. The user-submitted values are accessible by prefixing the form's NAME parameter after prefixing it with a $. As soon as we get to the PHP script, the form variables are available as $FirstName, $LastName, or whatever. No need for or any special decoding. We could reference $GLOBALS["FirstName"], but what's the point of cool features if we don't use them?

PHP functions

A quick look at PHP functions, and we'll get into this section's code. PHP function names are case insensitive but must include parentheses, even if the argument list is empty. Variables defined within a function are by definition local to the function. Unlike Perl, global variables are not within the scope of a function unless explicitly declared with the global keyword as on line 18. Another PHP keyword, static, indicates a variable should retain its value between function invocations.

The example in a nutshell

PHP documents can switch back and forth between HTML and PHP as often as your logic dictates. However, a PHP document always begins in HTML mode unless explicitly stated to the contrary. The first seven statements in form-one.php are the normal start of the document HTML. Line 9 indicates the start of a PHP segment with <?PHP. The <? characters can start a PHP segment, but the character pair also indicates the start of an XML segment. Let's play it safe and use the <?PHP alternative.

Good programming employs a decomposition methodology. A problem is partitioned into smaller and smaller logical components until it cannot be broken down any further. Ideally, each component in the program's main line should be a call to a subprogram. Following this procedure makes even complex programs easy to follow and helps with the goal of program maintainability.

The demo script calls itself when the user clicks on the form's submit button. The script must therefore determine if the access is the first time or a subsequent pass. Line 10 starts a ternary Boolean condition, with a twist. The ternary condition is actually a shortened if ... else construct. The basic syntax is:

Variable = (BooleanCondition) ? TrueAction : FalseAction;

Something like:

$AM_PM = ($Hours > 12) ? "PM" : "AM";

If $Hours is greater than 12, the variable $AM_PM is assigned "PM"; otherwise it's assigned "AM."

Since form-one.php is reentrant, an appropriate function must be executed depending upon whether it's the first or subsequent entry into the code. The form has a hidden field named FirstPass at line 46. $FirstPass will therefore be empty on the first pass and will have a value on subsequent passes. Hidden form fields are quite useful for preserving state, so brush up on their use if they're new to you.

The program's ternary condition could be coded as:

$FunctionReturn = empty($FirstPass) 
  ? ShowForm() 
  : ShowResults($FirstName,$LastName,nl2br($Comments));

$FunctionReturn would be set to the value returned by the called function. However, in this case we are only interested in the execution of the appropriate function, so the assignment is eliminated.

Note the function output of nl2br() being passed as a parameter to the ShowResults() function. The function nl2br($Comments) replaces any \n embedded in the $Comments string with the HTML tag <BR>.

The PHP predefined variable $PHP_SELF has a value containing the path and file name of the currently executing script. The action clause of a form uses the $PHP_SELF variable on line 45. The major advantage to using this variable, as opposed to hard-coding the script's name, is that the form will always call itself, even if the name of the file is changed.

Everything else in the example is fairly straightforward PHP and HTML. Let me emphasize one point, variable scooping. Variables defined within a PHP function live and die within the function. Variables defined outside the function, so-called global variables, are not visible inside a function. In this respect, PHP differs from most other languages. Global variables are accessible within a function if they are explicitly declared using the global keyword, as seen on lines 18 and 43. If a function's variable is to retain its value between function calls, the keyword static should start the variable declaration. Static variables are useful as counters.

Coming to a browser near you

Well, there you have it, sports fans, our first PHP exploration. In the second article in this series we'll pick up where we left off and add field validation and introduce check boxes, radio buttons, and drop menus to our bag of form tricks. We'll also build a generic form handler.

Where we go in the future is to a large part dependent on your feedback, so please let me know what you would like to see covered on these pages.

Urb LeJeune is a 25-year programming veteran with over 10 years of Internet experience thrown in for good measure.

Discuss this article in the O'Reilly Network PHP Forum.

Return to the PHP DevCenter.


Copyright © 2009 O'Reilly Media, Inc.