Building blocks for CGI scripts in PHP3

This tutorial provides and explains a kind of erector set for building Common Gateway Interface (CGI) programs with PHP. It is not an introduction to the language (at least, not a good introduction), but describes a collection of program fragments that can be combined, sometimes with slight modifications, to perform common CGI functions. It is intended for users who understand HTML and are willing to explore PHP and the CGI environment together.

Table of Contents

Recommended background

PHP is computer language developed for writing CGI scripts for use with the World Wide Web (Web). It is one of a collection of languages that are embedded within HTML documents (ColdFusion, Active Server Pages, etc.). That is, PHP commands are inserted among the lines contained in an HTML document.

PHP offers good support for document creators who want to integrate information from databases with their Web documents. To that end PHP offers simple interfaces to several database management systems: MiniSQL, MYSQL, Oracle, Sybase, PostGres/PostgresSQL, etc.

PHP began as a pair of tools: "Personal Home Page Tools," which later became the "Personal Home Page Construction Kit," and the "Forms Interpreter," written by Rasmus Lerdorf. These tools were later combined into PHP/FI, which evolved into PHP3, the topic of this tutorial. PHP implementations exist for Windows 95/NT, Macintosh, and most versions of UNIX.

For more information about PHP, you might want to review the PHP web site.

Some knowledge of HTML and HTML forms processing is necessary before learning to write PHP scripts; for background information about these topics, see

NCSA Beginner's Guide to HTML at
http://www.ncsa.uiuc.edu/General/Internet/WWW/HTMLPrimer.html
An instantaneous introduction to HTML forms and CGI scripts at
http://www.cc.ku.edu/~grobe/docs/other/forms-intro.shtml

Also, some experience with relational databases is probably necessary before learning to use the PHP interfaces to the various database systems, as well.

This tutorial is somewhat specific to writing scripts within the environment provided by the Unix operating system, in general, and on systems operated by ACS at The University of Kansas (KU), in particular. The general principles will hold for any environment hosting PHP, but some of the specifics may change.

Users of ACS systems usually store their HTML documents in a directory called public_html in their login directories. The PHP scripts they create are stored in a subdirectory of public_html called cgi-bin. Programs in this directory can be run as CGI scripts on most Unix systems operated by ACS at the KU (e.g., FALCON, EAGLE, LARK, RAVEN, etc.).

Writing PHP CGI scripts without forms

As mentioned earlier, this tutorial presents an erector set of PHP program fragments for performing tasks commonly performed with CGI scripts. These building blocks allow you to

Note that these building blocks are useful for building scripts that work both with and without forms. Since scripts that work without forms are simpler, we start with those and then enhance those scripts to work with data supplied by forms.

Most readers will find it useful to review the entire tutorial to get the big picture and then concentrate on those building blocks which they want to use in their own CGI scripts.

Sending an HTML document to the user

Most scripts will return a page of information (usually an HTML document) to the Web browser after a user submits a request for the script file. Such a page may do as little as thank the person for filling out the form; it may list the data that the user entered; or it may even contain another form that points to another script file.

PHP may be used to return an HTML document by using a program that really is just an HTML document. For example, suppose you want to build a script that simply returns the following document every time it is called:

<html> <title>My Thank You Page</title> <h1>Thank you for reading this document.</h1> See <a href="http://falcon.cc.ku.edu/~username"> my homepage</a> for more information.

Such a script could be constructed as follows:

#!/usr/local/bin/php <html> <title>My Thank You Page</title> <h1>Thank you for reading this document.</h1> See <a href="http://falcon.cc.ku.edu/~username"> my homepage</a> for more information. </html>

If this script is stored in a file called thanks.cgi within the cgi-bin directory within the username home directory on falcon.cc.ku.edu, the URL for the script would look like this:

http://falcon.cc.ku.edu/cgiwrap/username/thanks.cgi

The script would be started by the FALCON Web server whenever a Web browser requests this URL. Note that a PHP script can be used only on systems that have a PHP interpreter installed. The location of the interpreter must be specified on the first line of the script following a pound sign (#) and an exclamation point (!).

As you work through the examples below, remember that the first line of each PHP script must specify the location of the PHP interpreter, and on systems operated by ACS that line will be #!/usr/local/bin/php.

Note that this short PHP script prints a short HTTP (Hypertext Transfer Protocol) header before it prints the HTML document itself. This header includes the document "content type" (or MIME type) followed by two newlines, which cause a blank line to be sent to the WWW client, indicating the end of the header information and the beginning of the document itself. For more information about the HTTP header, see the references above.

CGI scripts present several security risks. To protect the user community, Academic Computing Services has installed special software called CGIWrap that must be used to start CGI scripts stored in user home directories. When the script starts, it runs as if you had started it while logged in to your account. That is, it will have potential access to the same files you can access when you run a command. As a result, you must be careful to build scripts that do exactly and only what you expect them to do, which is not always easy.

You can name the script file anything you want, but you might find it useful to use a name that ends with .cgi to remind you that the file contains a CGI script. You can use any text editor to create your script file. Note, however, that if you create your script file on your desktop system and upload it to one of the ACS systems, you must save it in "text only" mode and upload it in ASCII mode (using FTP or equivalent).

IMPORTANT: Your script files should probably give access permissions only to the owner. You can assign these permissions by entering

chmod 700 script_filename

Putting comments in your PHP scripts

PHP provides a way to put informational comments in your PHP scripts to help readers understand how the script works. These comments will be seen only by people reading your script file. Users who execute your scripts will not see them. Whenever PHP encounters two contiguous forward slashes (//), it ignores the rest of the line, so you can make your comments without interferring with the execution of the script.

Environment variables

Environment variables are variables defined within the operating system or shell at any given time. They typically hold information that may be useful to commands or programs running within the operating environment.

You may use any UNIX environment variable within a PHP script. To use an environment variable, use the PHP function getenv() send the environment variable name as an argument, as in getenv( variable_name ). For example, to use the REMOTE_HOST environment variable within an PHP script, use the function call getenv( "REMOTE_HOST" ). The following fragment prints the value of the environment variable that identifies the browser the user is using, HTTP_USER_AGENT:

#!/usr/local/bin/php <html> <head> <title>Print the working directory.</title> <body bgcolor="white"> <?php $browser = getenv('HTTP_USER_AGENT'); echo "The users browser is $browser"; ?> </body> </html>

In this example, PHP commands were inserted into the HTML documents by enclosing them within "<?php" and "?>" character strings. Alternatively, you may use the strings "<?" and "?>" or other delimiters discussed in the PHP documentation.

The following environment variables are established by the Web server, the PHP interpreter, and/or CGIWrap and may be used in PHP scripts:

DOCUMENT_ROOT
GATEWAY_INTERFACE
HTTP_ACCEPT
HTTP_ACCEPT_LANGUAGE
HTTP_FROM
HTTP_HOST
HTTP_REFERER
HTTP_USER_AGENT
IFS
MAILCHECK
PATH
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_PORT
REQUEST_METHOD
REQUEST_URI
SCRIPT_FILENAME
SCRIPT_NAME
SERVER_ADMIN
SERVER_NAME
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE

If you define an environment variable within your (parent) PHP script, (child) scripts started by your (parent) script may use it. If you start child scripts that change the values of environment variables defined in the parent script, however, the parent script will not see the changes: the child script cannot send information back to the parent via environment variables. Note that environment variable names are case sensitive.

Sending the contents of files and databases to the user

It is often useful to have a script send the contents of a file or database to the user. This section will demonstrate several techniques for doing this.

For example, suppose you have a signature file named

/home/username/public_html/signature.file

that contains a signature like

<p> See <a href="http://falcon.cc.ku.edu/~username"> my homepage</a> for more information.

and you want to use this signature with a page you send to the user from a script. You could do that with a script like:

#!/usr/local/bin/php <html> <title>My Thank You Page</title> <h1>Thank you for reading this document.</h1> <?php readfile ( "/home/username/public_html/signature.file" ); ?> </html>

The PHP function readfile() simply copies each line in the specified file to the browser, as soon as it is called.

Alternatively, you might first use the PHP file() function to copy the signature file into a PHP variable and then print that variable within a PHP "while loop":

#!/usr/local/bin/php <?php $SIG = file( "/home/username/public_html/signature.file" ); ?> <html> <title>My Thank You Page</title> <h1>Thank you for reading this document.</h1> <?php while ( list( $key, $line ) = each ( $SIG) ) { echo $line; }; ?> </html>

This approach assigns the contents of the signature file to the array variable $SIG and then uses that variable later as the document is being returned to the user. With either approach, the following document will be sent:

<html> <title>My Thank You Page</title> <h1>Thank you for reading this document.</h1> <p> See <a href="http://falcon.cc.ku.edu/~username"> my homepage</a> for more information. </html>

Including the contents of files in Web pages allows you to make changes to information that will be returned to a user by a script without changing the script itself. This can be very economical if many PHP scripts refer to the same file. For example, you could change your signature information for all documents returned by your scripts by modifying just your signature file instead of all your PHP scripts.

If another script or command has access to the signature file you are trying to copy to the user, your process may not be allowed to copy information from the file. For more information about this kind of problem, see the section titled "Sharing files among running scripts" below.

Finally, it might be useful to print the contents of a database. For example, if you have

  • an mSQL database on lark.cc.ku.edu named workshop,
  • containing a table named "netlist",
  • containing fields called "name" and "address",
you can print its contents using a PHP script like:

#!/usr/local/bin/php <html> <body bgcolor="white"> <h1>Here is a list of entries in the netlist database</h1> <p> <?php $link_id = msql_connect( "lark.cc.ku.edu" ); msql_select_db( "workshop", $link_id ); $sql = "SELECT first, last FROM netlist"; $result_id = msql_query( $sql, $link_id ); while ( $row = msql_fetch_array($result_id) ) { echo "$row[name] $row[address]&lt;br>\n"; } msql_close( $link_id ); ?> </body> </html>

The PHP msql_connect() function identifies the computer running the mSQL server and returns a "link identifier" that will be used in subsequent function calls. The msql_select_db() function opens the database to be used, and the msql_query() function sends an SQL query to the server. The msql_fetch_array() function requests the results of the query from the server and moves those results to a PHP variable.

mSQL will manage simultaneous accesses of the database, so that the program does not have to. Not all database systems supported by PHP will do so however.

PHP provides very strong support for accessing databases, including a separate set of functions for accessing each database management system (i.e., Oracle, mSQL, mySQL, etc.) it supports. (PHP support for databases is so straight-forward that PHP scripts might profitably be used by scripts written in other languages, such as Perl or C for project prototyping, etc.)

Running other scripts from yours

PHP allows you to call an external shell script from within a PHP script. In general, you can run a script and send the output of that script to the user by using the PHP system() function. system() takes the general form: system ( command_line, return_variable ) where
command_line
is some shell command (such as ls, cat, etc.), and
return_variable
is some value returned by the command as it executes.
This facility can be used to run file-resident shell commands as well as other PHP or shell scripts. For example, you can use this approach to include the current date in a document: #!/usr/local/bin/php The current date is <?php system ( "/bin/date", $return ); ?>

Any information written (to standard out) by the script will become part of the HTML document returned to the user. In this example, the date will appear in the HTML document as

The current date is Wed May 8 18:09:14 CDT 1996

This capability allows PHP users to utilize already existing commands and scripts supplied by the operating system or by other users.

An alternative approach is to assign the output of the called script to a PHP variable and then print the variable later. The next example uses the PHP exec() function to execute the UNIX date command. Each line of output is placed in the array variable named $INFO, and the first line returned, counting from 0, is placed in the variable named $DATE_INFO.

#!/usr/local/bin/php <html> <?php exec ( "/bin/date", $INFO, $return ); // execute the date command. $DATE_INFO = $INFO[0]; // copy the first line from the // returned array to $DATE_INFO ?> <title>Current date</title> <body> <?php echo "The current date is $DATE_INFO"; ?> </body> </html>

This approach is more convenient when you wish to process the information returned by the shell script before sending it to the user.

Putting a counter in a document

Counters are widely used on the World Wide Web to see how many people examine HTML documents. A counter is usually implemented as an ordinary file that is used to hold a single value--the number of accesses to a particular document. To build a counter, you must first create a count file. This file contains only the (ASCII) number at which you would like the counter to start. You can build a count file using any editor on your system. Assuming this file is called counter.file, a PHP script to use it could look like

#!/usr/local/bin/php <html> <title>My first return page</title> <h1>Thank you for selecting this document.</h1> <?php $fp = fopen("/home/username/counter.file", "rw"); # open the counter file with read and write access. $COUNT = (int) fgets( $fp, 100 ); // read the current value. // cast the string as an integer. $COUNT++ ; // increment it by one. $fp = fopen("/home/username/counter.file", "w"); fputs( $fp, $out); fclose( $fp ); echo "You are visitor number ", $COUNT; ?> </html>

This script reads the counter file into a string variable called COUNT, "casting" it as an integer variable, increments COUNT by one (by using $COUNT++, stores the new value in the counter file, and then returns an HTML document that uses the counter variable.

Sharing files among scripts

If multiple users run scripts that read and write to the same file at the same time, strange things may occur. It is possible, for example, that the two running scripts would read the current count at the same time, increment it by one at the same time, and store the new value in the file, reflecting access by just one user instead of both.

The chances of experiencing difficulties due to such concurrent access vary according to the type and frequency of access. In many cases, the frequency of document access is small, so the chances of simultaneous access are small enough to ignore. However to be safe, you should keep your data into a database management system that will handle simultaneous access, such as mSQL or Oracle, or write PHP code to protect your scripts. Such code is beyond the scope of this document, however.

Using PHP with forms

As you know from introductory reading, scripts can be started from HTML forms using the Common Gateway Interface supported by Web HTTP servers. If you are going to start a script from a form, create the form, carefully noting the names of your "fields" (the names of the places you leave for users to fill in data, such as "name" and "address" below); these will be important when you write your script. When you've created the form and you have some idea of what you want your script to do, then you're ready to start.

A simple example form

Suppose you want to build a form that collects e-mail address from users interested in vegetarianism. The following is an example.

<form method="post" action="http://www.cc.ku.edu/cgiwrap/grobe/send-veggi-info.cgi"> <P> If you would like more information about vegetarianism, please enter your name and e-mail address below.<P> Please enter your name:<br> <input type="text" name="name" size="35"><br> Please enter your e-mail address:<br> <input type="text" name="address" size="35"><p> <input type="submit" value="send address"> <input type="reset" value="start over"> </form>

This form would be rendered as follows by your Web browser:


If you would like more information about vegetarianism, please enter your name and e-mail address below.

Please enter your name:

Please enter your e-mail address:


You must identify a CGI script for each form that you create. Data from the form above will be processed by the script located at

http://www.cc.ku.edu/cgiwrap/grobe/send-veggi-info.cgi

The location of the script that processes information supplied by the form must be provided in the ACTION attribute of the <form> tag. For example, if you have an account on FALCON (falcon.cc.ku.edu), your account is called username, and you have a PHP script in the file script_file, then your form tag would look like this:

<form method="post" action="http://falcon.cc.ku.edu/cgiwrap/username/script_file">

A script to work with the simple example form

Once you've created your form, specified your script file, and given it the correct permissions, you're ready to start composing a PHP script to process your form data. You might use a very simple script to respond to this form:

#!/usr/local/bin/php <html> <title>Thank You Page</title> <h1>Thank you for filling out my form!</h1> </html>

However, this form does nothing with the data entered by the user. To actually use the data within a PHP script, you may use the HTML form field names in a special way within that script. PHP will create a PHP variable for every field named within any form data that is sent to it. For example, within the following script, $name refers to the contents of the "name" field in the example form above. The result page returned to the user will contain the actual name entered whenever the PHP variable $name is used:

#!/usr/local/bin/php <html> <title>Thank You Page</title> <h1>Thank you for filling out my form!</h1> Thank you, <?php echo $name; ?>, for filling out my form! I will mail information to <?php echo $address; ?> right away. </html>

Mailing information to users from a script

You can use a PHP script to e-mail information to you whenever users activate the "Submit form" button on your form. The PHP commands to do this take the following form. #!/usr/local/bin/php <html> <title>Thank You Page</title> <h1>Thank you for filling out my form!</h1> Thank you, <?php echo $name; ?>, for filling out my form! I will mail information to <?php echo $address; ?> right away. </html> <?php $message = "You have just sent info about vegetarianism to another interested person.\n" ; mail(grobe@ku.edu,"vegetarianism",$message,"From:grobe@ukans.edu" ); ?>

The mail() function takes four arguments:

  1. a blank-separated list of recipient e-mail addresses,
  2. a message subject,
  3. the body of the message, and
  4. a newline-separated list of additional headers. Reply-to: and Return: clauses can be appended to identify to whom any return message should be sent. These are not always the same as the From: address.

You can use the following PHP script fragment to send the information promised in the e-mail message above:

#!/usr/local/bin/php <?php $message = "Dear $name, Here are some books that talk about vegetarianism: Diet for a New America How to Avoid Beef "; mail($address, "Vegetarianism", $message, "From:grobe@ku.edu" ); ?>

In this example, "name" and "address" are names of fields specified in the example form, and their contents would be put in variables with the names $name and $address. Also, the concatenation operator (.) was used to concatenate strings in the above example. If you have two strings, say "xxx" and "bbb", you can concatenate them into one string "xxxbbb" by using the expression: "xxx" . "bbb".

Recording information in a file

To append data to a file, you can use a PHP fragment like the following: $fp = fopen ("/home/smith/filename", "a" ); fputs ( $fp, ". . ." ); fclose ( $fp ); where the information you want to record appears in place of the ellipsis (. . .) within a call to the PHP fputs() function. The information to be recorded is first prepared in a variable. In this example, it is prepared by concatenating several strings (some containing quotes preceded by a backslash (\") to make sure they are used as literal quotes. Alternatively, it could be prepared using the sprintf() function to arrange the information in a particular format.

If you plan to use the data in a database, you may want to use a standard comma-delimited format and add a .dbf extension to your filename as in:

#!/usr/local/bin/php <?php $fp = fopen ("/home/smith/list-of-recipients.dbf", "a" ); $line = "\"$name\",\"$address\"\n"; fputs ( $fp, $line ); fclose ( $fp ); ?>

The information written to the file would resemble

"Michael Grobe","grobe@ku.edu" "Megen Duffy","meg@ku.edu"

Typically, a file used to collect data must grant read and write permissions (600) only to its owner since PHP scripts started by CGIWrap run as if the owner of the file containing the scripts has started them manually while logged in. If permissions are assigned in this fashion, only the scripts owned by the file owner can read or record information in the file. The data remains relatively confidential.

Every time the script runs, it will append a name and address entry to the HTML in this file, so the guestbook list will continue to expand. You can use a PHP script to print the contents of this file, using one of the methods presented earlier.

Here is a script segment that will add a name and address to the mSQL database used earlier. This segment assumes that $name and $address have been defined from the form, and checked for special characters (by using a PHP routine such as addslashes() or quotemeta()).

<?php $link_id = msql_connect( "lark.cc.ku.edu" ); msql_select_db( "veg", $link_id ); insert_sql = "INSERT INTO netlist (name, address) VALUES ($name, $address)"; msql_query( $insert_sql ); msql_close( $link_id ); ?>

The PHP msql_query() function sends an SQL request to the mSQL server. In this example data is inserted into the database, and no data will be returned. Note that productional work would requre more stringent use of status checking on the miniSQL accesses. For example the msql_query function would probably appear as something like:

msql_query($sql, $link_id) or die ("Insert failed: " . msql_error());

The msql_error() function will return the most recent error. The " . " is used to concatenate the text string "Insert failed: " with the error message returned by msql_error().

For more information about using databases from PHP scripts see the ACS document Web-database integration using PHP

Handling checkbox and multiple select variables

Checkbox variables are handled somewhat differently from other form variable types. Typically, checkbox fields in an HTML form all have the same name, and the values collected from each field are sent separately by the Web client. When PHP receives the values, it places them into a PHP array with the same name used for the checkbox in the HTML form.

PHP programs will probably need to extract individual checkbox values from this array for specific purposes. Suppose, for example, that you want to find out what browsers your Web community uses. You could set up a survey form to collect and record information provided by a form containing a checkbox variable:

<html> <FORM METHOD=POST ACTION="http://www.ku.edu/cgiwrap/grobe/test-checkbox.cgi"> Please help us to improve KUfacts by filling in the following questionnaire: <P> Your organization? <INPUT NAME="org" TYPE=text SIZE="48"> <P>Which browsers do you use? <OL> <LI>Lynx <INPUT NAME="browsers[]" TYPE=checkbox VALUE="Lynx"> <LI>Mosaic <INPUT NAME="browsers[]" TYPE=checkbox VALUE="Mosaic"> <LI>Netscape <INPUT NAME="browsers[]" TYPE=checkbox VALUE="Netscape"> <LI>Internet Explorer <INPUT NAME="browsers[]" TYPE=checkbox VALUE="Explorer"> <LI>Others <INPUT NAME="browsers[]" TYPE=checkbox VALUE="Others"> </OL> Your e-mail address: <INPUT NAME="address" SIZE="42"> <P>Thanks for your input. <P><INPUT TYPE=submit value="Submit survey"> <INPUT TYPE=reset> </FORM> </body> </html>

On your browser this form would appear as


Please help us to improve KUfacts by filling in the following questionnaire:

Your organization?

Which browsers do you use?

  1. Lynx
  2. Mosaic
  3. Netscape
  4. Internet Explorer
  5. Others
Your e-mail address:

Thanks for your input.


When the form is submitted, the information the client sends to www.cc.ku.edu looks something like this:

POST cgiwrap/grobe/test-checkbox.cgi HTTP/1.0 Accept: www/source Accept: text/html Accept: video/mpeg Accept: image/jpeg Accept: image/x-tiff Accept: image/x-rgb Accept: image/x-xbm Accept: image/gif Accept: application/postscript User-Agent: Lynx/2.2 libwww/2.14 From: grobe@www.cc.ku.edu Content-type: application/x-www-form-urlencoded Content-length: 150 org=Academic%20Computing%20Services &browsers=Lynx &browsers=Mosaic &browsers=Netscape &address=grobe@ku.edu

Note that multiple values are sent for the checkbox variable "browsers".

The following script could be used to return a summary of the respondent's reply. This script collects the form information and then prints a list of each browser that was checked. PHP will return all of the values for the variable browsers in an array called browsers that can be referenced as $browsers.

#!/usr/local/bin/php <html> <h1>Thanks for filling out the survey</h1> We will record your information as follows: <?php echo $org; ?>uses the following browsers: <p> <ol> <?php while ( list( $key, $browser ) = each( $browsers ) ) { echo "<li>$browser\n"; }; ?> </ol> The contact address is:<?php echo $address; ?> </html> exit;

This script uses a while loop to print each value along with an <li> tag, so the values will appear as entries in an ordered list. The PHP each() function returns the current key/value pair in the $browsers array and sets the current index pointer to point to the next pair. Successive calls to each() allow a loop to examine each array entry.

The PHP list() operator breaks a key/value pair into its component parts and stores each part in a separate variable.

This script could be modified to record the reply on a data file or do other things with the data submitted.

The checkbox information in this example could have been collected by using a "multiple select" of the form:

<select multiple name="browsers"> <option> Lynx <option> Mosaic <option> Netscape <option value="Explorer">Internet Explorer <option> Others </select>

In either case the information submitted for the variable browsers will be handled the same.

Doing things selectively

The PHP if statement allows you to compose more complex scripts which do different things based on what the user submits in the HTML form. You could use the if structure to display special messages only to people with a certain name or domain name, for example. The if structure takes the following form:

<?php if ( some logical expression ) { some PHP commands } ?>

For example, suppose you would like to greet anyone whose name is the same as yours with a special message in your result page. You could enclose the following if structure inside your result page:

<?php if ($name eq "Megen") { echo "Hi Megen!"; } ?>

Each time a user submits a form which contains "Megen" in the "name" field, the user will be greeted with a return page which includes "Hi Megen!"

Alternatively, you can leave PHP mode following within the clause following the if and PHP will send any HTML encountered to the user. For example:

<?php if ($name eq "Megen") { ?> Hi Megen! <?php } ?>

will send "Hi Megen!" to any user whose name is "Megen", just as in the previous example.

PHP also supplies an accompanying else clause which allows even more latitude in constructing scripts. The else structure looks like:

if ( some logical expression ) { some PHP commands } else { some other PHP commands }

You could use the else clause to present a different message to any users who weren't named "Megen":

<?php if ( $in{'name'} eq "Megen" ) { ?> Hi Megen! <?php } else { ?> Hi Dude! <?php } ?>

The else clause returns, "Hi Dude!" whenever someone who is not named Megen submits the form. If the else clause were omitted, no greeting at all would be returned to such users.

Of course, the user might enter her name as "Megen Smith", in which case the comparison with "Megen" fails even though the user's name really is Megen. One way around this is to search for the string "Megen" within the field value submitted instead of testing for equality. You can use a PHP "regular expression search" to do just that as follows:

<?php if ( substr ( $name, "Megen" ) // then look for the string "Megen" { print "Hi Megen!"; } ?>

If the user enters a string that contains the substring "Megen" anywhere within it, she will be greeted as "Megen".

However, you really can't be sure whether Megen will type her name with a leading capital "M". If she types "megen" or "MEGEN SMITH", the if statement above will not respond with "Hi Megen!". There are other regular expression capabilitites within PHP that can help you deal with this problem. See the PHP tutorials for more information.

Sources of additional information

The text "CGI by Example" by Robert Niles and Jeffry Dwight provides several good examples of CGI projects implemented in PHP.

See also the comprehensive text "Core PHP Programming" by Leon Atkinson (Prentice-Hall, 1999).

Michael Grobe
Jan Grzymala-Busse
Megen Duffy
Academic Computing Services
The University of Kansas
First version: January 1, 1999
Current version: January 14, 1999