PHP DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


Using PHP to Interpret Forms
Pages: 1, 2

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.

References

• 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

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 CGP.pm 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.

 




Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!


Sponsored by: