CS 200 
Computer Science
from Ada and Euclid to Quantum Computing and the World Wide Web
cs200@cs.virginia.edu
Schedule - Problem Sets - Exams - Notes - Lectures - Links

Schemer's Guide to PHP

PHP, a recursive acronym for "PHP: Hypertext Preprocessor", is an open-source scripting language that is especially suited for Web development because it is easily embedded into HTML. This document should provide enough information to get started writing PHP programs, but you may need to consult the online PHP manual (available at http://www.php.net/manual/en/) to find out about primitive procedures in PHP that may be useful for your projects.

What distinguishes PHP from other "Internet" languages you may have heard of, like JavaScript, is that the PHP code is run ("executed") on the server. We can embed PHP directly in HTML pages by using a special sequence of characters — <? to indicate the start PHP code, and ?> to end. PHP is not built into HTML, but is an extension supported by many web servers, including Apache, the UVa server you will be using.

Element ::= <? PHPCode ?>
Here is an example web page that incorporates PHP:

<html>
<head>
<title>A PHP Web Page</title>
</head>

<body>
<p>This is HTML</p>
<?
   print "This is PHP.<br>";
   print "This is <em>still</em> PHP.<br>";
 ?>
 <B>Now we're back to HTML.</B>
</body>
</html>

When a browser requests the page above, the HTML will be displayed normally, but the PHP code will be evaluated on the server. The output of evaluating the PHP code is included in the resulting web page.

Here is the result: sample.php3. Note: It is important to name the file something ending in .php3. Otherwise, the server will not evaluate the PHP code.

Note that the HTML formatting in the PHP code still works. Everything we print in PHP code embedded in a web page end up in the HTML that is then displayed by the browser. Before reading further, try setting up a web page that uses PHP in your home directory.

Programming in PHP

PHP is a universal programming language — this means every process we could describe using in Scheme, we can also describe in PHP (we'll cover more formally what it means to be a universal programming language in class April 15th). The syntax of PHP is very different from Scheme, but many of the evaluation rules should be familiar.

The PHPCode in a web page is a sequence of instructions separated by semi-colons (;):

PHPCode ::= Instructions
Instructions ::= Instruction ; Instructions
Instructions ::=
PHP has many different kinds of Instructions. The three you will use most are assignment, applications and function definitions:
Instruction ::= AssignmentInstruction
Instruction ::= ApplicationInstruction
Instruction ::= FunctionDefinition

Assignment

Scheme is designed for a functional programming style. This means most of a Scheme program is applying and defining functions (and procedures). PHP is designed for an imperative programming style. This means most of a PHP program is assignments. In Scheme, we use set! to do assignment. In PHP, we use the = sign to mean assignment (to do equality comparisons, PHP uses ==):
AssignmentInstruction ::= Variable = Expression
In PHP, all variables must begin with the dollar sign ($).

To evaluate an AssignmentInstruction, PHP evaluates the Expression and places the value in the place named Variable. (Just like the Scheme evaluation rule for set!). The only difference is if there is not already a place named Variable, PHP will create a new place as a result of the assignment instruction. Hence, the PHP instruction $x = 1 will act like (define x 1) if there is no place already named x, and like (set! x 1) if there is already a place named x.

An expression in PHP is similar to an expression in Scheme — it is a code fragment that evaluates to a value. In PHP, expressions use infix notation. The operator is placed between the operands (except for function calls, described below). PHP supports most of the standard arithmetic operators. Here are some examples:

SchemePHP
(define four 4)
(define two (/ four 2))
(define bigger (< (* four four) 17)
(printf "four: ~a two: ~a bigger: ~a"
    four two bigger)

four: 4 two: 2 bigger #t

$four = 4;
$two = $four / 2;
$bigger = (four * four) < 17;
    Without the parentheses it would evaluate as
              (* four (< four 17)))
print ("four: $four two: $two bigger: $bigger");

four: 4 two: 2 bigger: 1

Note the PHP uses 1 to mean true. PHP considers the empty string and 0 to be false, and (almost) everything else true.

Applying Functions

In PHP, we apply a function to operands by following the name of the function with a comma-separated list of arguments surrounded by parentheses:
ApplicationInstruction ::= Name( Arguments )
Arguments ::=
Arguments ::= MoreArguments
MoreArguments Argument ,MoreArguments
MoreArguments ::= Argument
Argument ::= Expression
This is equivalent to (Name Arguments) in Scheme (except there are no commas between the arguments in Scheme).

PHP has many primitive functions. The Function Reference section of the PHP manual has subsections from I to CVIII (108) describing a riduculous number of functions provided by PHP. Luckily, you will only need to use a few of them. The last section of this document describes some of the more useful provided functions.

Defining Functions

Defining a procedure in PHP is similar to in Scheme, except: We define a function using:
FunctionDefinition ::= function ( Parameters ) { Instructions }
Parameters ::=
Parameters ::= MoreParameters
MoreParameters Parameter ,MoreParameters
MoreParameters ::= Parameter Parameter ::= Variable
For example,
SchemePHP
(define square (lambda (x) (* x x)))
(define quadratic (lambda (a b c x)
   (+ (* a (square x)) (* b x) c))
)
(display (quadratic 2 3 7 4))

51

function square ($x) { return $x * $x; } ;
function quadratic ($a, $b, $c, $x) {
    return $a * square ($x) + $b * $x + $c;
} ;
print quadratic(2,3,7,4);

51

PHP also provides a function create_function for making procedures the way you would in Scheme using lambda:
Expression ::= create_function (String1, String2)
The parameters are passed as the first string (as a comma-separated list), and the body is passed as the second string. For example, (lambda (a b) (+ a b)) would be create_function ('$a $b', 'return $a + $b'). Here's an example:
$adder = create_function ('$a,$b', 'return ($a + $b);');
print "Adding: " . $adder (2, 2) . "<br>";

Adding: 4

PHP does not evaluate applications the same way as Scheme, however. In particular, it does not create a new frame to with places for the parameters.

Control Instructions

PHP also provides several instructions similar to Scheme special forms. Two useful ones are if and while which are described below. PHP also support switch (similar to Scheme's case), for (similar to Java's for from 1 Feb's notes).

If

The if instruction is similar to Scheme's if special form:
Instruction ::= if (Expression) { Instructions }
is equivalent to (if Expression (begin Instructions)).

PHP also supports alternative clauses but uses else to distinguish them:

Instruction ::= if (Expression) { Instructions1 } else { Instructions2 }
is equivalent to (if Expression (begin Instructions1) (begin Instructions2)).

While

The while instruction repeats a sequence of instructions as long as the test expression is true:
Instruction ::= while (Expression) { Instructions }
Here is an example that will print out the first 10 Fibonacci numbers:
$i = 1;
$a = 1;
$b = 1;
while ($i <= 10) {
  print "Fibonacci $i = $b<br>";
  $next = $a + $b;
  $a = $b;
  $b = $next;
  $i = $i + 1;
} ;

Types

Like Scheme, PHP has latent (invisible) types that are checked dynamically. The three types you will find most useful are numbers, strings and arrays.

Numbers

PHP treats numbers like Scheme, except it does not do exact arithmetic. Instead of using fractions, everything is treated as either an integer or a floating point number. Here are some examples:
SchemePHP
(define four 4)
(define pi 3.14159)
(define half 1/2)
$four = 4
$pi = 3.14159
$half = 1/2     (evaluates to 0.5)

Strings

PHP treats strings like Scheme: they need quotation marks. You can use single quotes (') or double quote ("). However, there is a very important difference — when you use double quotes variables in the string are evaluated, but when you use single quotes they are not.

Here are some examples:

SchemePHP

> (define name "spot")

> (display "See spot run")

See spot run

> (display (list "See" "name" "run")

(See name run)

> (display (list "See" name "run"))

(See spot run)

$name = "spot";
print 'See spot run';

See spot run

print "See $name run";

See spot run

print 'See $name run';

See $name run

You can concatenate (run together) two strings by using the dot (.). So, alternatively, we could have used:
print "See " . $name . " run";
If you want a literal quote to appear in a string you print, use \":
print "My name is \"Spot\".";

Arrays

PHP doesn't have lists, but it has arrays which are the next best thing. An array is actually a list of (key, value) pairs. A PHP array is similar to the frame's we implemented for the Mini-Scheme evaluator — there is a way to add a new (key, value) pair to a frame, and there is a way to lookup the value associated with a key. For our Mini-Scheme frames, the key was always a symbol, and the value could be any Mini-Scheme value. In PHP, the key can be either a non-negative integer or a string; the value can be any PHP value.

We can set the value associated with a key using: using:

SetInstruction ::= Expression [ Expression ] = Expression
We get the value associated with a key using:
FetchExpression ::= Expression [ Expression ]
The first expression in a fetch expression must evaluate to an array.

Here are some examples:

$yellow['red'] = 255;
$yellow['green'] = 255;
$yellow['blue'] = 0;
print '(' . $yellow['red'] . ', ' . $yellow['green'] . ', ' . $yellow['blue'] . ')';

(255, 255, 0)

Another way to create an array is to use the array function. For example, this code is equivalent to the three assignments above:
$yellow = array ('red' => 255, 'green' => 255, 'blue' => 0);
If we leave out the keys, PHP will create an array using the integers (starting from 0) as the keys:
$presidents = array ("George Washington", "John Adams", "Thomas Jefferson", "James Madison", "James Monroe");
print $presidents[0];

George Washington

print $presidents[2];

Thomas Jefferson

print $presidents[5];

James Monroe

print $presidents[42];


   There is no value matching key 6. PHP does not report an error, it just evaluates to the empty string.
$presidents[42] = "George Walker Bush";
print $presidents[42];

George Walker Bush

(Note that without anything else, the web page this generates is:

George WashingtonThomas JeffersonGeorge Walker Bush

There are no new lines or spaces between the print commands.

Of course, we can put arrays in arrays, just like we can make lists of lists in Scheme. Here is a more complicated example:

$presidents = array (
  1 => array ('name' => "George Washington", 
              'bill' => "$1"),
       array ('name' => "John Adams",
              'college' => "Harvard" ),
       array ('name' => "Thomas Jefferson",
              'bill' => "$2",
              'college' => "William and Mary" ),
       array ('name' => "James Madison",
              'college' => "Princeton" ),
 43 => array ('name' => "George Bush",
              'college' => "Yale" ));

foreach ($presidents as $president) {
  print "Name: " . $president['name'] . "<br>";
  print "Bill: " . $president['bill'] . "<br>";
  print "College: " . $president['college'] . "<br><p>";
}
This produces:

Name: George Washington
Bill: $1
College:


Name: John Adams
Bill:
College: Harvard


Name: Thomas Jefferson
Bill: $2
College: William and Mary


Name: James Madison
Bill:
College: Princeton


Name: George Bush
Bill:
College: Yale

We use 1 => for the first element of the array, so the keys start counting from 1 instead of 0.

We use the foreach construct to do something to all the elements in the array, similar to the Scheme map procedure:

ForEachInstruction ::= foreach (Array as Variable ) { Instructions }
is the same as:
(map (lambda (Variable) Instructions) Array)

Getting Input

If you talk to almost any web developer, they will tell you that the best thing about PHP is that it transparently parses HTTP_POST data. Then they will do cartwheels out of sheer glee. This is just fancy jargon for "The computer acts smart (for once)."

For every form element with a name="Name" parameter in your HTML form, PHP will create a variable with the name $Name and assign it whatever data the user entered.

If the user entered no data, the variable will be assigned an empty string. You can then reference those variables like any other PHP variable. For example, you could put them into a SQL statement.

For the example form:

<FORM METHOD="POST" ACTION="form.process.php3">
 First name: <INPUT TYPE="TEXT" NAME="FirstName"><BR>
 Last name: <INPUT TYPE="TEXT" NAME="LastName"><BR>
 Comments:<BR>
  <TEXTAREA ROWS="3" NAME="UserComments"></TEXTAREA><BR>
 <INPUT TYPE="SUBMIT"><INPUT TYPE="RESET">
</FORM>

PHP will assign the variable $FirstName to the text the visitor entered in the input named FirstName. We can use that just like any other PHP variable. For example, here is the file form.process.php3 that processor the form above:

<?

  print "Thank you for your information!";

  print "<BR>";

  print "Name: " . $FirstName . " " . $LastName . "<BR>";

  print "Comments: " . $UserComments;

?>

You can try it here:

First name:
Last name:
Comments:

Is that cool or what? In your situation, you'll often be using the user input to create a SQL command to insert, select or update from your database.

Using SQL

Before reading this section, read the SQL Guide.

PHP provides procedures for interacting with a database using SQL. You can call these procedures like any other PHP procedure. The PHP evaluator will send the appropriate commands to the SQL database.

Before using any SQL commands, you must connect to the database server and open a database. Do this using mysql_connect (hostname, username, password). The hostname for the ITC database is dbm1.itc.virginia.edu; the username and password are those you used to create your database account. Then, use mysql_select_db (name) to select the database. The name of the database should name the name of the database you created.

Here is the set up code from the http://www.cs.virginia.edu/cs200/notes/presidents.php3 example:

  $hostName =  "dbm1.itc.virginia.edu"; 
  $userName =  "dee2b"; 
  $password =  "quist"; 
  $dbName =  "dee2b_presidents"; 
  
  mysql_connect($hostName, $userName, $password) 
    or exit("Unable to connect to host $hostName"); 
  
  mysql_select_db($dbName) 
    or exit("Database $dbName does not exist on $hostName");  
Note how we use or exit("...") after the calls to mysql_connect and mysql_select_db to fail gracefully if there is an error.

Next, you will probably want to send a SQL command to the database. This is done using mysql_query (SQL Command). The SQL Command is just a string that is a SQL command. For example,

  $result = mysql_query("SELECT lastname, firstname FROM presidents " .
			"WHERE college='William and Mary' ORDER BY lastname");
The command can be any PHP string, so long as it is a valid SQL command.

The call to mysql_query returns a resource that can be used to get information about the SQL result. In the example, we assigned the result to $result.

There are several PHP procedures for getting information about the result of a SQL command. All of these take the value returned by a call to mysql_query as their first parameter.

PHP Function Arguments Description More Information
mysql_num_rows result Returns the number of rows in the SQL result http://www.php.net/manual/en/function.mysql-num-rows.php
mysql_num_fields result Returns the number of fields in the SQL result http://www.php.net/manual/en/function.mysql-num-fields.php
mysql_field_name result
field_index
Returns the name of the column in position field_index from the SQL result http://www.php.net/manual/en/function.mysql-field-name.php
mysql_result result
row_index
field_index
Returns the value in row row_index and field field_index from the SQL result http://www.php.net/manual/en/function.mysql-result.php

Here are some examples:

  // Determine the number of rows 
  $numrows = mysql_num_rows($result); 
  $numcols = mysql_num_fields($result); 
  
  // print the results 
  print "<table border=0 cellpadding=5>"; 
  print "<tr>";

  for ($k = 0; $k < $numcols; $k = $k + 1) 
    { 
      print "<th>" . mysql_field_name ($result, $k) . "</th>"; 
    } 

  print "</tr>";

  for ($i = 0; $i < $numrows; $i++)  // $i++ is short for $i = $i + 1
    { 
      for ($j = 0; $j < $numcols; $j++) { 
        print "<td>" . mysql_result ($result, $i, $j) . "</td>"; 
      } 
      print "</tr>"; 
    } 
  print "</table>"; 
At the end of your PHP program, you should close the database using mysql_close ().

Primitive Procedures

PHP has thousands of built-in functions (primitives). And even better PHP also has one of the best online sources of help in the world. The manual provides details on every single function built into PHP, we will only describe a few of them here. 

PHP Function Arguments Description More Information
exit message Ends the current script, printing the error message for the user to see. http://www.php.net/manual/en/function.exit.php
date format Returns the current date and time in the given format. See PHP guide for full list of formats.  
header text Writes text to the HTTP Header. Basically, if you write header("Location: www.virginia.edu"); then the user will be automatically zapped to www.virgina.edu. This is very useful for form processing. http://www.php.net/manual/en/function.header.php
str_replace find
replace
string
Replaces all instances of find with replace in the given string. http://www.php.net/manual/en/function.str-replace.php
strcmp str1
str2
Compares two strings. strcmp returns 0 if the strings are identical, and number less then 0 if str1 is alphabetically less than str2. The == operator won't work to compare strings, you need to use (strncmp (s1, s2) == 0). http://www.php.net/manual/en/function.str-replace.php
stripslashes string Run this function on any string after you select it from a database. It removes the slashes from \' used to store ' in strings in the database. Don't worry about why, just do it. http://www.php.net/manual/en/function.stripslashes.php
addslashes string Run this function on any string before you insert it into a database. Don't worry about why, just do it. http://www.php.net/manual/en/function.addslashes.php

For more information

See the PHP Manual: http://www.php.net/manual/en/.

Credits: This guide was created by Portman Wills and David Evans.


CS 655 University of Virginia
Department of Computer Science
CS 200: Computer Science
David Evans
evans@cs.virginia.edu
Using these Materials