transplanted goose

tech Talk, v1n6

You're not a programmer, but you're reasonably comfortable with HTML. You want to be able to do some simple programming on the web (such as forms) without waiting for your project to move to the top of your IT folks' project list.

Take heart - there's a new programming language on the block, and it's working its way into the repertoires of programmers and non-programmers alike. It's called PHP, it's free, and it is completely compatible with HTML. But enough with the chit-chat - let's get down to business.

Web-based forms typically have two components - an HTML file that solicits information from a user, and a script that processes that information in some way. For example, a comment form typically solicits feedback from a user, then sends it to someone via email. For this column I've created a simple comment form in PHP and HTML, which I'll walk you through step by step, but first, three things you need to know about PHP:

  1. PHP file names typically have a ".php" extension - check with your IT folks to see what they require.
  2. PHP statements are included inside angle brackets, using the following structure: <?php some PHP statement(s) ?>. Unlike HTML, you can include multiple PHP statements inside the angle brackets.
  3. In UNIX or LINUX environments, PHP files must be executable. If you don't know how to do this, talk to your IT folks.

OK, let's get started. I've created a simple web form that does the following:

  1. Displays a web form with three fields: name, email address, and comments box.
  2. Once the user fills in the box and clicks the submit button, emails the input to someone, then displays a thank you note on the screen.

Below is the HTML and PHP code (let's name it form.php ) that will accomplish this:

   1: <?php
   2: if ($FormSubmit) {
   3: process_form(); # $FormSubmit is not blank
   4: } else {
   5: display_form(); # $FormSubmit is blank
   6: } #end of if ($FormSubmit)
   7:
   8: function display_form() { # Display form for user input
   9: global $PHP_SELF;
  10: ?>
  11: <html>
  12: <head>
  13: <title>Comment Form</title>
  14: </head>
  15:
  16: <body>
  17: <h1>We Want To Hear From You</h1>
  18:
  19: <p>Please fill in the form below to tell us what you think; you will
  20: receive a response within 24 hours.</p>
  21:
  22: <form action="<?php echo $PHP_SELF; ?>" method="post">
  23: <p><input type="text" name="Name" size="30"> Your Name<br />
  24: <input type="text" name="Email" size="30"> Your Email Address</p>
  25:
  26: <textarea name="Comments" cols="65" rows="3"></textarea><br />
  27: <input type="hidden" name="FormSubmit" value="Yes">
  28: <input type="submit" value="Submit Your Feedback">
  29: </form>
  30: </body>
  31: </html>
  32: <?php
  33: } #end of function display_form()
  34:
  35: function process_form() { # Process form after user clicks on the submit button
  36: global $Name;
  37: global $Email;
  38: global $Comments;
  39: global $FormSubmit;
  40:
  41: #Email comments to someone
  42: $to = "noone@somewhere.com";
  43: $subject = "Feedback Form";
  44: $message = "Name: $Name\nEmail: $Email\nComments: $Comments";
  45: #This line is optional, but useful for replying to the sender
  46: $header = "From: $Name <$Email>\r\nReply-To: $Email\r\n";
  47: mail ($to, $subject, $message, $header);
  48:
  49: #Provide web response to user
  50: ?>
  51: <html>
  52: <head>
  53: <title>Thank You!</title>
  54: </head>
  55:
  56: <body>
  57: <h1>Thank You!</h1>
  58:
  59: <p>Thank you for your feedback - here's what you wrote:</p>
  60: <hr />
  61: <p><strong>Name: </strong> <?php echo "$Name"; ?> <br />
  62: <strong>Email: </strong> <?php echo "$Email"; ?> <br />
  63: <strong>Comments: </strong> <?php echo "$Comments"; ?> </p>
  64: <hr />
  65: <p>If you included an email address, you should receive a reply within
  66: 24 hours. Thanks again for your feedback.</p>
  67: </body>
  68: </html>
  69: <?php
  70: } #end of function process_form()
  71: ?>

The first thing you'll probably notice is that HTML looks like HTML, and PHP doesn't. To help you visualize these differences, I've used color-coding: red for HTML, black for PHP, blue showing you where the PHP code starts and ends, and yellow for comments (information that is useful for anyone reading the program, but not part of the program itself).

Most programs are written in chunks, starting with the easiest, smallest task and building from there (just like web publishing). Let's take a look at this script, piece by piece.

Lines 11-31: this section should be easily recognizable as an HTML document; note the HTML element at the beginning and end. If you look closely at the code, you'll see that it creates a simple web form.

There are two special features of this web form:

  1. Line 22 uses a bit of PHP code to define the action in the FORM element. $PHP_SELF is a special PHP variable (placeholder for data) that refers to the current document. When the user clicks on the form's submit button, the server looks to this same file for instructions on what to do next.
  2. Line 27 contains a hidden variable ($FormSubmit) that is used to determine whether the form has been filled out or not.

Lines 51-68 should also be easily recognized as an HTML document, this time a response thanking the user for the feedback and letting the user know what was sent. Note the use of PHP in lines 60 and 62 ; the variable names correspond to the ones used in the HTML form (see lines 23, 24 and 26). Variables in PHP are indicated by using a dollar (or string, $) sign in front of the variable name. Note also the use of angle brackets to format the user's email address.

Lines 8, 33: these lines of code form a wrapper, called a function, around a piece of a program. Note the name of the function - display_form() - which is descriptive enough to give you an idea of what the function does, in this case display the web form for user input. A comment in plain English (notice that it begins with a #) provides additional information to the person reading this program. Functions are a very important part of programming in PHP - they allow you to group statements (commands) together to accomplish a purpose, then execute that group of statements in another part of the program. This allows you to create extremely efficient programs - experienced programmers always look for ways to accomplish the task with the least amount of code.

Line 9: this is a declaration that indicates that the $PHP_SELF variable will be used in the function. The use of the "global" keyword indicates that this variable is available throughout the program; if "global" were not included, this variable would be local only to this particular function or a particular statement.

Lines 35, 70: another function wrapper, this time for the process_form() function.

Lines 36-39: these variable declarations provide placeholders for the data passed from the web form; declaring them here actually reads the data in from the form. Note that the names correspond exactly to the names used in the form (lines 23-24, 26-27), with the dollar sign prefix indicating a PHP variable. Names in PHP are case sensitive - $Comments and $comments are two separate variables - so it's important to be careful. Consistency is an important part of programming style; most programmers adopt naming conventions for variables and functions. In my case, I capitalize variable names, and in the case of compound names like $FormSubmit I capitalize each individual part of the name; for functions I use lower case and underscores, but I could just as easily use something like displayForm() instead of display_form(). The parentheses in function names serve a special purpose, as you'll see in the next section, just like the dollar sign in front of a variable name. Many programmers also adopt styles for spacing, indenting, and comments. The most important thing is to be consistent.

Lines 42-47: these 5 lines create the body and headers of an email message, then send it. The email recipient ($to) used here is a dummy one - you would obviously change this to a real address before you implemented the form. Line 44 creates the body of the email message. The '\n' creates a line break, and begins the text following it on a new line (it's often referred to as the newline character). Line 46 , which is optional, provides some additional email headers, in this case the From: and Reply-to: fields, which allows the recipient to use their email software's Reply feature. The '\r' before the newline character in this line is required for UNIX mail servers, so be sure to include it. Finally, line 47 sends the email message. The mail() function is a built-in PHP function.

There's just one final step before we can run our program, and that's to actually execute the functions we've created. This is where that hidden variable ($FormSubmit) from our web form comes into play.

Lines 2-6 are the keys to this little script. They introduce a condition into our program that essentially reads, "If the $FormSubmit field is not blank (in other words, it exists), then go ahead and process the form; otherwise (else), just display the form." The first time the program is run, it should skip the first part of the conditional statement and display the form, because it doesn't find the $FormSubmit variable. But once the form has been displayed, that hidden field fills in a value for $FormSubmit, and the next time the program is run (when the user clicks on the form's submit button), the program processes the form as instructed.

And that's it - all that's left is to try it out, but since our server doesn't currently support PHP, you'll have to put it on your own local server to do that (make sure you change the email address to your own so that you see how it works).

As you can see, it's not complicated when you break it down. Of course, if this were a form you were planning to implement, you'd probably want to add some additional features, like the ability to make corrections to the data before it's submitted, add some security to the form by validating a user's email address before the information is sent by email, and check to make sure that required fields have been filled out so that incomplete information isn't sent on to the recipient.

What we've seen here is just the tip of the iceberg. One of PHP's greatest strengths is its ability to integrate HTML and SQL databases into web-based database applications - that's when you really start to cook. But that's a whole series of articles that maybe one day I'll write...

Related Links:
PHP (the official home of PHP on the web)
PHPBuilder (articles, forums, code library, mail archive)
Introduction to PHP (C|Net)
Code for this script

Published in NewBreed Librarian, volume 1, number 6, December 2001 - archived at
<https://scholarsbank.uoregon.edu/dspace/handle/1794/1071>

(web links have been updated where applicable; expired web links are shown in bold)

© 2001, colleen bell about
transplantedgoose.net / words