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.
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
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.).
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
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.
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:
Such a script could be constructed as follows:
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:
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
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:
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:
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.
For example, suppose you have a signature file named
that contains a signature like
See
my homepage 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:
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":
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:
See
my homepage for more information.
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
\n";
}
msql_close( $link_id );
?>
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.)
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
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.
This approach is more convenient when you wish to process the
information returned by the shell script before sending it to
the user.
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.
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.
This form would be rendered as follows by your Web browser:
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
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:
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).
Recommended background
Writing PHP CGI scripts without forms
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.
Sending an HTML document to the user
Thank you for reading this document.
See
my homepage for more information.
Thank you for reading this document.
See
my homepage for more information.
Putting comments in your PHP scripts
Environment variables
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
Sending the contents of files and databases to the user
Thank you for reading this document.
Thank you for reading this document.
Thank you for reading this document.
you can print its contents using a PHP script like:
Here is a list of entries in the netlist database
Running other scripts from yours
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:
Putting a counter in a document
Thank you for selecting this document.
Sharing files among scripts
Using PHP with forms
A simple example form
Sources of additional information
Michael Grobe