CPSC 120, Spring 2002, Lab 10:
Introduction to Web Site Programming with PHP

SOME WEB PAGES ARE static: All you can do is look at them and read them. Some have animated graphics or sounds, but you can still just look at them and listen. Some pages, however, are interactive. Interactive web pages allow you to input commands or data and to get some kind of response. This lab will teach you a bit of interactive Web page programming.

There are many ways to program interactive Web pages. We will look at just one: PHP. PHP is a server-side Web programming language. That is, the program code is actually executed by the Web server computer, where the Web page comes from, and not by the computer on which you are running your Web browser and using the page. PHP is most commonly used with Web forms. You fill out a form on the Web page. The information in the form is sent back to the Web server when you click the submit button. The sever runs a PHP program which examines the information and decides what kind of response to send. The PHP program actually writes a Web page containing the response. That page is sent back to your browser, and your browser displays the page. As far as you are concerned, all that happens is that you click on a button and you get a response. The Web browser, Web server, and PHP program work together to produce that response.

PHP is a serious programming language, with many features. A typical Web application is a complicated thing. Obviously, you will only be getting a small taste of PHP and Web programming in this lab. Hopefully, however, it will give you a better perspective on programming than you can get from a single language like xTurtle. You will find that many ideas introduced in xTurtle -- including variables, assignment statements, loops, if statements, and subroutines -- carry over to PHP, with some change in notation.

To get some idea of how PHP works, consider this Web form:

What is your name?
Pick a color:

When you click the button, your input is sent to a PHP program named colors.php. (Try it!) Here is that program:

     <?php

        print("<html><head><title>Color Reading</title></head>");
        print("<body bgcolor='#EE8888' text='#8800AA'>");
        print("<h1 align=center>Your Psychological Color Profile</h1>");

        if ($user == "") {
           print("<h2>Greetings, Anonymous Coward</h2>");
        }
        else {
           print("<h2>Greetings, $user</h2>");
        }

        print("<p>Here is what your color choice reveals about your personality:</p>");

        if ($color == "Red") {
           print("<p>People who like <b>red</b> are lively and ready to rock!</p>");
        }
        else if ($color == "Blue") {
           print("<p>People who like <b>blue</b> are calm, ");
           print("good natured, and tend to have a lot of friends.</p>");
        }
        else if ($color == "Green") {
           print("<p>People who like <b>green</b> are sensitive, ");
           print("but are easily taken advantage of.</p>");
        }
        else {
           print("<p>People who like <b>Gray</b> are probably lying.</p>");
        }

        print("</body></html>");

     ?>

This program starts with <?php and ends with ?>. Between these two lines are the actual commands of the program. (A PHP file can include other stuff besides php commands, but in this lab we will only consider programs of this form.) The PHP program must be in a file that ends with .php. This is how the Web server knows that the file contains a PHP program.


Output

The purpose of a PHP program is to write the HTML source code for a Web page. The print command is used to output text onto the page. The text that you print should be legal HTML code. For example,

           print("<h1 align=center>Your Psychological Color Profile</h1>");

will add a centered headline reading "Your Psychological Color Profile" to the page. Note that the print command -- like most individual commands in PHP -- must end with a semicolon. The parentheses and quotes are also required. You are not allowed to use double quotes inside other double quotes. So, if you need quotes in the HTML code, you should use single quotes. For example, in the above PHP program, single quotes are used around the color specifications in the line:

           print("<body bgcolor='#EE8888' text='#8800AA'>");

Variables

Like any other programming language, PHP uses variables to store values. PHP is a little unusual, however, in that a given variable can store any type of value, including both numbers and strings. Variables don't have to be declared. When the computer encounters a variable name for the first time, it automatically creates space for that variable.

A variable name in PHP must begin with a $. The operator that is used to assign a value to a variable is = (rather than the := that is used in xTurtle). An assignment statement must end with a semicolon (;). Other than that, assignment statements and expressions are similar in PHP and xTurtle. For example:

           $area = 17 * 42;
           $name = "Fred";
           $count = $count + 1;

Variables can be used inside output strings. When the string is output, the value of the variable will be substituted for the variable. For example, if the value of the variable $name is the string "Fred", then the statement

          print("<h2>Hello, $name</h2>");

will actually output <h2>Hello, Fred</h2>, and this will result in displaying Hello, Fred as a level-2 headline on the Web page. (Note that the double quotes in the assignment statement $name="Fred" are not actually part of the value of the variable. In a program, quotes are placed around a string to tell the computer that it's a string, but the actual string is the stuff inside the quotes.)

By the way, one difference between PHP and xTurtle is that PHP is case-sensitive. That is, upper and lower case letters are not equivalent. For example, "IF" is different from "if", and $name is different from $Name.


Predefined Variables

Before a PHP program is executed, certain variables are automatically created and given values. You can use these variables in your program. The values of these variables give you information about the request that was sent from a user's Web browser to your program. For example, the value of $REMOTE_ADDR is the so called "IP-address" of the computer where the Web browser is running. More important, when your program is used to process the data from a Web form, the data is placed in variables that you can use in your program. The values of these variables tell you what information the user entered in the form. Here's how it works: Every input element in a Web form has a name. This name is specified as part of the HTML source code that creates the element. This same name -- with a $ added to the front -- becomes the name of a variable in your program. The value of the variable is the value that the user entered in the input element. For example, a text input box could be created in a Web form with the HTML source code

           <input type=text name=first>

In a PHP program that processes the form data, there would be a predefined variable named $first whose value is the text that the user entered into the box. For example, in the following form:

Give me two numbers
and I will multiply them!
   

The text input boxes are named "first" and "second". The form is processed by the following PHP program, which uses $first and $second to refer to the numbers entered by the user:

   <?php

      
print("<html>");
      print(
"<head><title>Web Multiplication Service Results</title></head>");
      print(
"<body>");
      print(
"<h1>Your results</h1>");
      print(
"<p>Here are the results from your multiplication problem:</p>");
      print(
"<p>You asked me to multiply $first times $second.</p>");
      
$answer $first $second;
      print(
"<p>Let's see... I think the answer is $answer.</p>");
      print(
"</body></html>");   

   
?>

IF Statements

Every programming language needs loops and branches. For branching, PHP uses if statements. These are similar to IF statements in xTurtle, but the syntax is somewhat different. As in xTurtle, it's convenient to distinguish three types of if statement:

        Simple if:

            if ( <condition> ) {
               <statements>                  // The statements are done only if
            }                                // the condition is true


        Two-way if:

            if ( <condition> ) {
               <statements>                  // These statements are done if
            }                                // the condition is true
            else {
               <statements>                  // These statements are done if
            }                                // the condition is false


        Multi-way if:  

            if ( <condition> ) {
               <statements>                  // These statements are done if
            }                                // the first condition is true.
            else if ( <condition> ) {
               <statements>                  // These statements are done if
            }                                // the first condition is false
               .                             // and the second is true.
               .
               .
            else {
               <statements>                  // These statements are done if
            }                                // all the conditions are false.
      

Note that braces, { and }, are required to group statements that are inside an if statement, and parentheses are required around the condition. The words "if" and "else" must be written in lower case. And the final "else" part of a multi-way if statement is optional. Note that the multiway if statement uses "else if" where xTurtle uses "or if".

In a condition, the operators <, >, <=, and >= can be used in the usual way. However, to test equality, you must use the double equal sign operator ==. (This is because the = operator is used for a different purpose, the assignment operator.) A very common mistake in program is to try to use = instead of == to do a comparison. Unfortunately, this is not considered to be a syntax error, so you won't get any warning about it from the computer. If you want to test whether two things are not equal, use the inequality operator, !=. You can use the words and and or to combine two tests, but these operations are more commonly written && (for "and") and || (for "or"). For example, the test

         if ($first == "" || $second == "")

tests whether $first is the empty string or $second is the empty string (or both). We could use this test to improve the multiplication program given earlier, so that it gives the user an error message when the user has not filled in both of the input boxes:

         if ( $first == ""  ||  $second == "" ) {
            print("<p>You have to fill in both boxes to give me something to multiply!</p>");
            print("<p>Please go back and enter both numbers.</p>");
         }
         else {
            print("<p>Here are the results from your multiplication problem:</p>");
            print("<p>You asked me to multiply $first times $second.</p>");
            $answer = $first * $second;
            print("<p>Let's see... I think the answer is $answer.</p>");
         }

Loops

PHP has several kinds of loop. We will consider just one example, which is as similar as possible to loops in the xTurtle language. In xTurtle, a LOOP continues until you tell it to EXIT. In PHP, it is possible to make a loop that will continue until you tell the computer to "break" out of the loop. A loop that does this has the form:

        while (true) {
        
            <statements>
            
            if ( <condition> ) {
               break;
            }
            
            <statements> 
            
        }

The "while (true) {" marks the beginning of the loop. The final "}" marks the end. The computer executes all the statements between these two lines until it gets to a "break;" statement, which tells it to break out of the loop. A break statement can come anywhere inside the loop, although it only really makes sense to have it inside an if statement. (The word "true" can actually be replaced by any <condition>, and then you don't need the break statement. The computer will end the loop if this condition becomes false.)

Here is an example of a loop that puts a "countdown" from 10 to 0 on the Web page:

         $count = 10;
         while (true) {
            print("<h3>$count...</h3>");
            if ( $count == 0 ) {
               break;
            }
            $count = $count - 1;
         }

For a more complex program that uses loops and if statements, you can look at this calendar. The calendar is produced a PHP program. It always shows the current month, and the current day is shown in red. You can look at the source code for this program. It uses some built-in subroutines and other PHP features that you won't understand, but you can copy the source code for the calendar into your own PHP program if you want to add a calendar to your page.


Subroutines

Subroutines in PHP are referred to as "functions" (somewhat illogically). A function is called in PHP in the same way that a subroutine is called in xTurtle: just by giving the name and a list of parameters enclosed in parentheses. However, a semicolon must be added at the end of a function call statement in PHP. For example, print is a predefined function in PHP, and the print statements that you have been seeing throughout this lab are function call statements.

The definition of a function is PHP is similar to the definition of a subroutine in xTurtle, except that it starts with the word function instead of with the word sub and it uses { and } to group the statements that are inside the subroutine. (Also, of course, the dummy parameter names start with $.) Here is an example of a function declaration:

        function multiPrint($output,$times) {
           $count = 0;
           print("<h3 align=center>");
           while (true) {
              print("$output<br>");
              $count = $count+1;
              if ($count >= $times) {
                 break;
              }
           }
           print("$lt;/h3>").
        }

This function is meant to be called with a string as its first parameter and a positive integer as its second parameter. It produces a centered headline containing multiple copies of the string. The second parameter tells how many copied to include. For example, the function call statement

           multiPrint("PHP Rocks",5);

would produce this on the Web page:

PHP Rocks
PHP Rocks
PHP Rocks
PHP Rocks
PHP Rocks

PHP functions can be recursive. An example can be found in my Random Sentence Page. The PHP program for this page contains recursive functions that generate a sentence based on a BNF grammar. The sentence is generated based on random choices among various alternatives in the BNF rules. Every time the page is loaded, a different sentence can be generated. You can look at the PHP source code. The BNF grammar is given in a comment at the top of the program. (Comments in PHP are enclosed between /* and */. This program uses "switch" statements, an alternative branching statement that makes it easy to choose among several alternatives. But you don't need to understand the switch statement.)

By the way, as you might notice in this example, functions in PHP do not need to be defined before they are used. A function definition can come later in the program than the line that calls the function.


Sessions (This Section is optional!)

In some ways, programming for the Web is a little peculiar, because of the way interaction with the user is handled. The user sends some data, usually by filling in a form. A Web server responds by sending back a Web page to be displayed to the user. There is no built-in provision for continuing interaction, such as when the user plays a game. Each move that the user makes has to be a separate event, with a new Web page as a response. The Web server has built-in way to remember what is going on from one page to the next. It doesn't even know that the page requests are related. Fortunately, PHP has a way of remembering the data for you. You just have to set up a "session". A session is a sequence of related page requests. You can "register" a variable so that its value will be carried over from one page to the next. All the pages that are to be part of the session must start with:

                <?php
                session_start();

You can't even have a blank line or a space before the <?php. Then, you can register the variables that you want to be part of the session. This is done with the session_register() function. For example:

                <?php
                session_start();
                session_register("count");
                session_register("number");

This says that the variables $count and $number will be valid throughout the session and will maintain their values from one page request to the next. Note that the parameter to session_register() is a string that gives the name of the variable without the $.

Although sessions are an advanced topic, you can try a Web guessing game that uses them. You can also look at the PHP source code for this game. The program does not use a loop, because each of the user's guesses will be a separate page request. The entire program is run for each page request. Between page requests, the program keeps track of the number the user is trying to guess and the number of guesses the user has made so far. These values are stored in the variables $number and $count, which are registered as session variables. The first time the user visits the page, $count is zero because the user has not yet made any guesses. If this is the case, the computer picks its random number and sets $count to 1. When $count is greater than zero, the computer looks at the user's guess and compares it to $number. It gives a response based on whether the user's guess is equal to the number, less than the number, or greater than the number. If the user's guess was wrong, the program places a form on the Web page that the user can use to make the next guess. (The user's guess is stored in the variable named $guess. The value of this variable actually comes from a Web form, which has an input box named guess.)

In serious Web programming, sessions are used in applications such as shopping carts and user account logins. In a shopping cart application, session variables can be used to keep track of the items that the user has placed into the cart as the user browses from page to page. On Web sites that have user accounts, the user can log in on one page, and session variables can be used to remember who the user is, as the user browses various pages on the site. If you can understand how the guessing game examples, you can get some idea what it takes to program such applications.


Beyond Sessions

A session allows you to save data between page requests, but a session only lasts as long as the user's Web browser program is running. If a user exits from the Web browser program, and then returns to your site later, all the session data from the first visit is gone. Some method is needed for saving data over an even longer term. There are two places where data can be stored for the long term: files and databases. This is not something that is unique to PHP. Lots of programs use files or databases for long term storage of data. Here, we'll look briefly at databases, which work especially well with PHP.

A database is simply a structured collection of data stored on a computer's hard disk. (The data is actually stored in files, but the database provides extra structure that makes it easier to insert, find, and modify individual items of data.) The most common type of data is a relational database, in which all the data is stored in tables. Each column in the table has a name that describes the data in that column. Generally, all the data in a given row of the table is related in some way. For example, a "contacts" table might have columns named "lastname", "firstname", "email", and "phone". One row of the table would contain some person's names, email address, and phone number. A specialized programming language called SQL is used to access the data in a database. SQL includes commands for inserting new rows in a table, deleting rows, modifying data in a row, and finding rows that satisfy a specified condition.

PHP has built-in functions that allow a PHP program to access a database by sending SQL commands to it. We are going to look at neither SQL nor the PHP database functions. However, I have set up some database tables for students in this class, and I have written a few special purpose functions for accessing them. You will use these tables in one of the exercises for this lab. The functions are defined in the PHP program database_example.php. To see the source code for this program, click here. You will copy this program and use it as the basis for your own programs.

The sample program has a "page counter" that counts the number of times the page has been accessed. The value of the page counter is stored in the database. The database is also used to keep a list of comments that have been submitted. You can add a comment to this list with the following form. The data from this form is processed by another PHP program, named getcomment.php. You can look at the source code for that program if you want. After you fill out and submit the form, you can go back to database_example.php to see that your comment has been received:

Enter your comment here:
          

Here is the basic information you need about using the database:

Connecting. Before you can do anything else with the database, you must connect to it by calling the function connectToDB($username,$password). The parameters are your username and a database password which will be assigned to you individually. If your username is jsmith and your password is letmein, then the command in your PHP program would be:

           connectToDB("jsmith","letmein");

Accessing your first table. You have two database tables in which you can store data. The first one contains a numbered list of items. Each item can be any text that you like (up to 65,535 characters). There are three functions for accessing the data in this table. The function countTextItems() returns an integer that tells you how many items have been stored in the database. If you say

           $num = countTextItems();

then the value of $num is the number of items. The items are numbered 1, 2, 3, ..., $num in the order in which they were added to the database. If you want to get a specific item from the database, use getTextItem($number). The value of the parameter is a number that specifies which item you want. The function returns the item, so that you can assign it to a variable. If you say

           $text = getTextItem($i)

and if the value of $i is a number in the correct range, then the value of $text will be set to the corresponding item from the database. If you want to add a new item to the database, use addTextItem($text) where the value of the parameter gives the text item to be added. You can change the text associated with a given sequence number by calling replaceTextItem($number,$text). Finally, each item has a "time stamp" that is set when the item is first added to the database and whenever it is modified. It tells you how old the item is. If you say $timestamp = getTextTime($number), then $timestamp will be a string that represents the time stamp of the item with sequence number $number. The string will be of the form "March 30, 2002, 12:49 PM", for example.

Accessing your second table. The second table in your database is simpler. Each row of the table contains a "name" and a "value". You can associate a value with a given name, and you can retrieve the value associated with a name. (Names can be up to 32 characters long; values can be up to 255 characters.) This is a very general idea, and you can use this table in many different ways. There are only two functions for accessing this table. Use setDBValue($name,$value) to set the value associated with a given name. Use $val = getDBValue($name) to retrieve the value that was associated with the specified name. If no value was associated with the specified name, this function will return the empty string.


Exercises

The following exercises should be finished by April 12, the Friday following the lab. In exercises 1 and 2, you are asked to create Web pages and PHP programs. The work for these exercises must be in your www directory. Note that a PHP program will not work if you load a file directly into your browser. You must access it through a URL of the form http://math.hws.edu/~username/.... This is required because a PHP program is executed by a Web server. If you load the file directly, it doesn't go through the Web server. When you use a http:// address, you are sending a request to a Web server, which will produce a response in the appropriate way..

Note that copies of all the sample PHP programs mentioned on this page, as well as the HTML source code for this page itself, can be found in the directory /home/cs120/php. You will want to copy some or all of these files into your own account. You will at least need to get a copy of database_example.php, since it contains functions that you will need in the PHP programs that you have to write for Exercise 2.

Exercise 1:  For this exercise, you should write an HTML file that contains a form and a PHP program that processes the data from the form. The form should contain some questions that the user can answer, and the PHP program should produce a response that incorporates the user's answers in some way. The first two forms on this page are examples of this sort of thing, but your work should be a little longer and more imaginative.

Exercise 2:  Write a PHP database application that collects comments from users and makes it possible for users to view all the comments that have been submitted. You will need three files: an HTML page with a form where the user can enter a comment; a PHP program to process the input from this form by adding the comment to the database; and a PHP program that displays all the comments. The third form on this page shows how to get a comment from the user, with a php program, getcomment.php for storing the data in a database. Furthermore, database_example.php shows how to retrieve a comment from the database. You can use these as models, but you should do something more meaningful. For example, you could make a "guest book". You could ask users to respond to a question on some controversial issue or to write a review of some movie. Or you could ask them to contribute their favorite joke.

Exercise 3:  Write a short essay comparing PHP to the xTurtle programming language. Turn in your answer on paper, along with the Web addresses that I should use to access your solutions to exercise 1 and 2.


David Eck, 30 March 2002