# Using PHP For Interactive Web Pages

## Introduction: What is PHP?

When I first started writing web pages, I found it frustrating that, while it was easy to create nice looking forms in plain HTML, it was much more difficult to set up my site to actually respond to (or even record) data submitted via a form. Fortunately, as the web has grown, so have the tools available to handle such tasks. Simple processing of form data is now reasonably easy and allows a web site to become much more interactive. In this article, I present an overview of PHP as one of the useful tools for adding interactivity to a web site beyond a set of hyperlinks. The name is one of those cute self-referential acronyms, the PHP Hypertext Preprocessor. While PHP is a full programming language, it is designed to make adding basic interactivity to a web page easier than it would be with Java applets or CGI programs. In particular, PHP makes it very easy to handle data submitted from a standard HTML web form. PHP code is embedded into a standard web page, where it is set off with tags. (Some variations are permitted on the exact syntax of the tags.) When a browser requests a PHP page from the server, the server scans the contents of the page, then runs the code in the tags and replaces the tags and their content with the output of the code before sending the page to the browser. Since the code is embedded directly into the page, PHP is fairly quick to write and easy to maintain. PHP is not the only language to use such a technique -- Microsoft's Active Server Pages and server-side JavaScript both work similarly. PHP is the open-source variation on this common theme.

Andrew Bennett is Professor of Mathematics at Kansas State University.

Despite being based on C syntax, PHP is fairly easy to use. Part of the ease of use is because it is an interpreted language, i.e. you just type the code directly into the web page. You don't need to provide any headers or other control codes for your program -- you can include just a single line of code if you want. So, while PHP provides a full programming language, you can use as little of the language as you want. In addition, you update your program just by updating your web page. Since the output of PHP is just standard HTML, PHP works with any browser without any plug-ins. PHP provides easy hooks to access other programming languages, including the GD library for images and numerous database systems. You can also link to general processes running on the server -- though doing so can open security holes.

A PHP page can also include JavaScript code and applet tags to include Java applets. However, communication between the different languages is problematic because PHP code is executed by the server before the page is sent to the browser, while (client-side) JavaScript and Java are run by the browser. The PHP code can output JavaScript function calls or Java PARAM tags, so PHP can send results to JavaScript or Java. On the other hand, to send results from Java applets or JavaScript functions to PHP code, it is necessary to put the results into GET or POST variables and send them to the server with a request to (re-)load a web page.

## A Simple Example

My first example is an easy web form. While standard HTML provides many elements to make it easy to produce good looking forms for a web site, it has traditionally required some CGI programming to do anything with the data submitted. With PHP, it is easy to create a page that accepts the data and either e-mails it to the instructor, saves it to a database, or takes some other action depending upon what is submitted.

For this example, I've put together a reaction form for students to describe a section in their calculus textbook. I have found it useful to ask students to read the section in the text before lecture and turn in a note card at the beginning of lecture with either a short summary of the section or a question they wished to have answered (the "muddiest point" in the section). I distribute the cards to recitation teachers so they have a sense of where the students in their recitations are having difficulties. It would be helpful to have the material available in time to respond to it in lecture directly, but since few students can profitably identify difficult areas more than one section ahead of the lecture, I can't realistically collect cards before lecture. I can let them e-mail their responses, however, and I read selected e-mail an hour before lecture. My experience with other assignments is that I get much better feedback if I provide more structure by having the student fill in an online form rather than just write an e-mail -- even if I carefully indicate the specific questions and the structure to use in writing the e-mail. A more complete discussion of the use and advantages of online preparatory assignments, though from the point of view of teaching Physics, can be found in Novak et. al. (1999).

The web form is written in one page. The action element of the form tag directs the input to a second page that packages the input into an e-mail message to the instructor and prints a short confirmation for the student. The Sample Form in the links is live, so you can test out the interaction before (or after) looking at the source code. I've also included a link to a typical response as it arrives in my email. (Links will open in a new window.)

Note that jittform.html is a standard HTML form, without any PHP code at all. The response page, jittresp.php, does include PHP code, but that won't show up if you look at the page source in your browser, as your browser has received only the output of the code from the server. (The full source is listed on the last link above.) In PHP, variables do not have to be declared, since they follow a standard syntax of a $followed by a variable name (with the usual limitations of no spaces, alphanumeric, etc.). Any data posted by a form are automatically placed in a variable with the same name as the corresponding form element. So$query will hold the input from the textarea with the name query on the form and so forth. Note that branching statements in PHP affect the plain HTML located between the {} of the PHP code, even though the HTML code doesn't lie inside <?php ?> tags. So this code from jittresp.php

<?php
$msg="Name:$name

Email:
$email Summary:$summary

Problem:
$query"; if (mail("bennett@math.ksu.edu","Section 3.3 -$name",$msg)) { ?> Your preparatory material has been mailed to the instructor. Thank you. <?php } else { ?> The system was unable to mail your material. Please press the back button on your browser and try again. If the problem persists, please contact the instructor via email at <a href=mailto:bennett@math.ksu.edu>bennett@math.ksu.edu</a> <?php } ?>  will produce either the confirmation that the mail was sent or the error message depending on whether the mail function returns true or false. This example is designed to show how little PHP code is needed for a useful page. Since PHP is a full language, it would be possible -- not particularly difficult -- to provide for a number of additional features, such as • including the student responses on the confirmation page, • allowing students to check their work and choose whether to edit or submit their answers, or • logging responses to a database rather than sending them via e-mail. Warning: I recommend that you configure your e-mail client to direct e-mail with subject "Section 3.3" to a separate inbox if you use this form in a large lecture. ## A More Complicated Example Having given one example of a very simple PHP page, I'd now like to show the power of PHP with a much more complicated example. This example is extracted from an online homework system for Trigonometry. The question page randomly generates a problem of finding the length of a circular arc, given the central angle and the area of the associated sector. It also includes a scale illustration of the situation created on-the-fly by PHP. After the student submits an answer, the answer page checks the answer and either marks it correct or, if incorrect, gives the correct answer and a link to a solution page that shows how to solve the problem in detail, including references to specific pages in the text. In the full online system, each student logs in and the pseudorandom number generator is seeded uniquely for each attempt by that student. The results are written to a database, with some care taken for the security of the system. In this open example, the pseudorandom number generator is seeded by the system clock. (Links open in a new window.) You may find it instructive to compare the source code in the links above with the page source displayed by your browser, to see the output of the PHP code, which replaces the material in the <?php ?> brackets. In particular, note that none of the database code is visible in the page source displayed by your browser, since the database calls didn't produce any output. In this way, database information that the program needs (including passwords) aren't visible to the end user. Working with string variables is a little different in PHP from many other languages. In particular, in the line (from question.php) echo "An arc in a circle subtends a central angle of$deg$dgsym ";  produces the output An arc in a circle subtends a central angle of 91°  where the "$deg$dgsym" is automatically replaced by the value of the variables$deg and $dgsym inside the string. No concatenation operator is required. Of course, a concatenation operator may be needed when there is no space or special character between a string variable and a constant string. This automatic conversion of string variables simplifies many situations where you want to output string values to the web page. In picture.php, there is an example of the creation of images in PHP. PHP links to the GD library to create Portable Network Graphics, which show on modern browsers and avoid the patent issues associated with GIFs. You call a PHP image with the same <img> tag as a regular image. consider the following lines from question.php: echo"<td><imgsrc=picture.php?t=$deg$dgsym&a=$a"."cm&s=?+cm ";
echo "height=200 width=220 align=right>\n";


(Note the use of the concatenation operator . since the variable a is followed by the string "cm" without any spaces). The output of these lines is <td><imgsrc=picture.php?t=91°&a=46.1cm&s=?+cm height=200 width=220 align=right>  where the values for t and a are randomly generated each time the page is loaded. This <img> tag produces the image The ability to pass GET variables (the values after the first "?" in the src value) allows the main PHP page to create dynamically an image to display during the processing of the code on the page. I have found this one of the most useful aspects of working with PHP. ## Additional Features In the best tradition of open source software, PHP has accumulated an enormous set of functions that implement features from a wide variety of other tools and languages. The Function Reference section of the online documentation has 108 chapters on different varieties of functions. For example, there are functions supporting over a dozen different databases. There is support for regular expressions in both POSIX and Perl Compatible varieties. The BCMath library for arbitrary precision arithmetic is included. There is support for XML data. And of course, like any modern language, PHP allows you to define, create, and use objects. With such a wide range of features, it is important to remember that you don't have to use anything you don't want. While PHP provides the option to use whatever tools appeal, you can do quite well sticking to just the basics. There are two special features of the language besides the enormous function set that are worth noting, both relating to PHP's flexibility in dealing with strings. First, PHP lets you use strings in many places where other languages restrict you to integers. For example, you can build arrays with string indices (associative arrays) in addition to the usual integer-indexed arrays. There are a wide variety of array functions available to retrieve and sort both values and keys (indices) from associative arrays. These arrays are particularly useful because the language contains built-in associative arrays of form variables (HTTP_POST_VARS, $HTTP_GET_VARS) that can be used to design a generic form response system that doesn't depend on knowing the specific form elements in advance. If you are used to using associative arrays and regular expressions in PERL, you can use a lot of the same techniques in PHP -- though typically in more readable form. PHP also allows you to use strings as the cases of a switch statement. The second special treatement of strings by PHP is illustrated by the following code snippet. <?php$a="hello"
$b="a";$c=${$b};
?>


This code assigns the value "hello" to the variable $c. The${} construction refers to the variable whose name is given by the string within the brackets. The brackets can even contain a function, as long as it produces a string that forms a valid variable name. Similarly, you can use a string to invoke a function. For example, the code snippet

<?php
function triple($a) { return 3*$a;
}

$f="triple";$x=7;
$y=$f($x); ?>  assigns the value 21 to the variable$y. These techniques give you much of the power of pointers in C. Unfortunately, they also give you the power to create many (though not all) of the bugs associated with pointers.

## Getting Started

PHP is open source and can be obtained free of charge from http://www.php.net/. You can get versions for a variety of operating systems, including Windows 95/98/Me, Windows NT/2000/XP, Mac OS X, and Unix/Linux. (Most Linux distributions now include PHP.) The web server must be configured to run PHP on appropriately labeled files, so it is necessary that the system administrator approve the use of PHP on your site.

PHP is becoming quite common. The most recent Netcraft survey (as of April, 2002) shows PHP in use at over 9,000,000 domains covering almost 1,200,000 different IP addresses. And Security Space's survey of Apache module use shows that PHP has had steady growth in market penetration over the last three years and is now the most commonly used Apache module, with about 45% market share.

The PHP web site has complete online documentation for the language. For those who prefer their documentation in hard copy, an amazon.com search turned up 44 PHP books. My favorite is Professional PHP Programming in Wrox's Programmer to Programmer series. This is an older book (by Internet standards -- published 1999), and there are likely good manuals among the newer books that I haven't looked at yet.

## Conclusion

The World Wide Web was conceived as a way of linking together resources from computers all over the world into one seamless web. This means that programming for the web is a different experience from traditional programming. One aspect of this is that, since the web is designed to link together many different resources, it makes sense to use many different tools to create interactive web experiences for users. In some ways, this is forced on developers. Even a basic set of tools for web development would include some image editing software to prepare images for the page, in addition to some way of creating HTML pages (possibly just a basic text editor). Typically a developer would also want sound and video software and programming tools to add interaction.

It is important to note the plural in the term "programming tools." Too many programmers, coming from a traditional background, think in terms of a programming language, rather than a set of tools. The glory of the web is that it enables many different pieces to work together. Different languages make different tasks easier and harder. It makes sense in this environment to use the tool for each task that makes that task easiest. For example, I have written (and maintain) an online homework system used by several hundred students a year, mostly engineers. I am often asked what language the system is written in. This is the wrong question, for the system consists of pieces written in five different languages: HTML, PHP, SQL, JavaScript, and Java. Each language was the best solution to the need for a particular feature in the system.

This approach of using multiple languages often raises questions about maintenance. Using just one language supposedly makes it easier to maintain a site, since the maintainer, who will eventually be someone other than the developer, will have to master only one language. Furthermore, the maintainer will have to track new versions of only one language and will have fewer compatibility issues to worry about. This is a false savings, however. Using the right language for each task leads to simpler and more easily maintained code than stretching the abilities of one language to its fullest.

The real requirement is that we quit thinking of programmers as people who have mastered one language. No one would expect a plumber or a doctor to understand how to use just one tool. Both are expected to have mastered a range of tools and techniques to use when appropriate. In the same way, developers need to have mastery of a range of programming tools. Fortunately, my experience with undergraduate programmers is that they have picked up on this and are quite comfortable switching tools as needed.

This specialization of tools also has advantages for the non-expert. Some mathematicians enjoy programming, but not all. But even mathematicians who don't want to master Java or some other language may want to get some specific interaction into a class web site. It is much easier to learn just enough of the correct tool to accomplish a task than to master programming in Java or C or Perl or whatever language is currently popular. For many situations, I have found PHP to be the correct tool.

## Bibliography

Castagnetto, J., H. Raway, S. Schumann, C. Scollo, and D. Veliath (1999), Professional PHP Programming, Wrox Press .

Novak, G., E. Patterson, A. Gavrin, and W. Christian (1999), Just-In-Time Teaching: Blending Active Learning with Web Technology, Prentice Hall.