Applied Systems Programming

Class Notes
Text: Programming the World Wide Web, 2nd Edition (Sebesta)
Dr. Tim Margush – University of Akron – © 2003

Chapter 12 – PHP (An Introduction)

PHP stands for "PHP: Hypertext Preprocessor". Everyone makes a big deal about how clever this name is, calling it a recursive acronym (because the PHP abbreviation is formed from the first letters of the three words: PHP, Hypertext, and Preprocessor and the abbreviation is also the first word). I will not make a big deal about this. I will tell you, however, that it is NOT an acronym (although it is recursive), but rather an initialism. An acronym is a pronounceable abbreviation (like POT, short for POrtable Toilet) made from initial sequences of words in the phrase being abbreviated. I have never heard PHP being pronounced (ffffffffp?). An initialism is an abbreviation that is vocalized by speaking each of the letters in sequence (like HTML). There are those who will criticize this distinction saying an acronym need not be pronounceable; such individuals redefine words so they can appear to be right when they are wrong. It would be easier to redefine wrong, then they could always be right:) OK - I am done not making a big deal about this.

Originally, PHP stood for Personal Home Page which was a package developed in 1994 by Rasmus Lerdorf to implement a page counter.

A PHP application is a combination of HTML and script, integrated so it appears to be an extension of HTML. The embedded PHP commands are processed on the server-side and are replaced by the result of the commands. PHP documents are requested in the same way as a standard html document (through a GET or POST request). The server recognizes the request for a PHP document by the file extension (php, phtml, php3, php4, ... ) and, if PHP capable, and invokes the PHP interpreter to translate the PHP file to a standard HTML document.

The PHP interpreter copies HTML code from the original document to standart output. PHP commands are processed and their output is copied. This is a lot like a Perl script, except that you do not have to print everything to stdout; print-ing is implicit. The resulting document shows no evidence of the PHP script, only the output of the script is included.

Any HTML document can be turned into a PHP document by changing the extension. The PHP interpreter will simply copy it (no processing takes place) and the document will be served as before. PHP commands can be added to a document via the traditional HTML script tag, or the shorter <?php script goes here ?> format. Remember that the PHP code is not passed on to the browser, so there is no need to obey any HTML syntax specifications when adding it to the file. However, you may want to validate PHP documents, so the second version is the only option for XML and XHTML syntax. Sharing PHP scripts is easy via the include command.

<?php
...
include("commonscript.txt");
...
?>

Note that a PHP include file is copied directly to the output unless a script is encountered (i.e. another <?php ... ?> tag).

Variables in PHP begin with '$' and are case sensitive. PHP reserved words and PHP functions ore not case-sensitive, so no more variable names like $If or $wHiLe. Typing is automatic and variable (as in Perl and JavaScript); no declarations are needed. Statements end with semicolons and comments can be written in Perl or C++ syntax.

Data types in PHP include scalars: integer, double, string, and Boolean; compound types: array and object; and special types: NULL and resource. NULL has one value, NULL, which is the value of an unbound (uninitialized) variable. This value can be coerced to 0 or "" and can be tested for with the isSet function. Variables can be "unbound" via the unSet function.

Integer and double values in PHP correspond to the long and double types in C. Strings are made up of 0 or more characters, each a single byte value. String literals behave in PHP as they do in Perl, so "\n" is a length 1 string, whereas '\n' has length 2. Double quoted strings may extend over multiple lines - each line break is like the \n character. The period (dot) character is the concatenation operator for strings.

Type conversions can be specified explicitly.

$x = (double)$x;
$x = doubleVal($x);
setType($x, "double");

all represent the same thing. The functions for int and string are intVal and stringVal. The type of data in a variable may be extracted by

getType($x) //returns a string like "integer"

or tested by one of the following Boolean functions:

is_integer($x)
is_string($x)
is_double($x)
is_bool($x)
is_array($x)
is_object($x)

PHP scripts create output using echo, print, or printf.

echo "<ol><li>$fav1</li>",
	"<li>$fav2</li>",
	"<li>$fav3</li></ol>";

Print is similar, except it requires a single item to print, never a list.

Printf allows formatting ala C. Consult the manual for details!

Arrays in PHP are associative - that is they allow strings as subscripts. The following array definition is quite legal:

$zip[44302]="Akron";
$zip[33240]="Kent";
$zip["Kent"]=44240;
$zip["Akron"]="44302, 44325, 44303";
$zip[]="This is very interesting";

This array is created implicitly. The last statement assumes a subscript that is one larger than the largest numeric subscript previously used, in this case 44303. The array 'construct' can also be used to create an array:

$scores = array(35, 56, 43, 65, 11);
$grades = array("Tim"=>56, "Sue"=>67);
$empty = array();

Arrays can be cleared and individual array elements can be removed using unset:

unset ($scores[2]); //position 2 is now empty
unset ($grades["Sue"]);
unset ($grades);

Arrays can be split and joined as in Perl and JavaScript. Explode uses a non-empty string for a delimiter and returns an array; implode concatenates the array contents placing a delimiter string between elements.

$arrayform = explode(" ", "This is split on spaces");
$strform = implode(":|:", $arrayform);

The keys (subscripts) and values of an array can be accessed directly using the array_keys and array_values functions. These create arrays subscripted 0, 1, 2, ...

$justSubscripts = array_keys($grades);
$justValues = array_values($grades);

This provides one method of traversal of an array using a traditional for loop. You can also get the number of elements in an array by using the count function, as in $numElts = count ($grades);

There is a foreach construct that is especially designed for arrays.

foreach ($grades as $key => $item){
	echo "<li>\$grades['$key'] is $item</li>";
}

You can leave out the 'key =>' part if you only need the values. This construct is different from that of Perl in that the $item variable is a copy of the array element, so changing it will not affect the array.

Arrays also support iteration through the use of an internal notion of a current element. You reset current to the beginning of the array using the reset function. The each function returns an array containing the current subscript(key)/value pair and advances current. If there are no more elements, each will return false.

$example = array("Fred" => 27, "Jean"=>29, "Harold"=>13);
reset ($example);
while ($key_value = each($example)){
   echo "<li>Key is $key_value[0] and value is $key_value[1]</li>";
}

The array assignment is sometimes written as follows to avoid the subscripting in the key/value pairs obtained. It uses the list construct which allows assignments to a list of variables.

list($key, $value) = each($example)

Arrays can also be manipulated with the array_push, array_pop, array_shift, and array_unshift (and a lot of other) functions. The push and unshift functions add at the end or beginning, returning the new number of elements. New elements are stored using numeric subscripts starting at 0. Existing numeric indices are adjusted in the case of unshift. Pop and shift return the removed item. Unshift renumbers the remaining items that have numeric subscripts.

Sorting is easy:

sort($example, SORT_NUMERIC);
asort($example, SORT_STRINGS);
ksort($example, SORT_REGULAR);

The sort function is used to sort values. All associations are lost as the sorted array will be keyed by integer subscripts 0, 1, 2, ... . The optional second argument (SORT_REGULAR is the default) will alter the behavior of the sort.

The other sorts maintain the key/value associations, sorting by the values (asort) or by the keys (ksort). Rsort, arsort, and krsort will sort in descending order. There are variations on these (usort) that allow a comparison function to be passed to do custom sorting.

Functions in PHP are defined with the keyword function.

function paragraph($content){
	return "<p>$content</p>";
}
print paragraph("This is a paragraph");

Functions may appear at any point in a PHP script; they need not be declared before they are used. Function calls may have more or fewer arguments than parameters; extra arguments are ignored, extra parameters are unbound. Arguments are passed by value unless either the argument or the parameter is preceded by an ampersand. 

function foo($flexible, &$byReference){
	$flexible++;
	$byReference++;
}
$a=1; $b=2;
foo($a, $b); //(byVal, byRef) $a is unchanged 
foo(&$a, $b);//(byRef, byRef) both are changed
foo(&$a, &$b);//(byRef, byRef) both are changed

Variables found inside a function are local unless declared (ha! that is a novel idea!) as global. Their lifetime is the duration of the function, unless declared static.

function globalvar(){ 
   global $x; ... 
   static $s = 0;
}

This states that the variable $x in this function should be bound to the memory associated with $x at the global level. The variable $s will be created and initialized once: the first time the function is called. Future calls will reuse the same memory location for $s and $s will retain its value between function calls.

Form submissions to a PHP file causes the creation of variables for each form widget. The PHP processor parses the query string and creates these variables that are then available to the script as it is interpreted. The widget names match the variable names (with a $ added of course). Since form handling scripts often need to process files, it is natural to expect file related functions in PHP.

$my_file = fopen("filename.dat", "r"); //or r+, w, w+, a, a+
flock($my_file, LOCK_SH);
$file_str = fread ($my_file, filesize ("filename.dat"));
flock($my_file, LOCK_UN);
fclose($my_file);

File locking is advisory, as it is in Perl. Support for cookies is available:

setcookie("sugar"); //unset this cookie
setcookie("butter", "cookie value", 0); //cookie has session duration
setcookie("oatmeal", "yum", time()+3600); //cookie expires in 1 hour

If a cookie is sent along with a request for a PHP document, the cookie value will be found in a variable such as $butter.

PHP also automates session tracking which does not rely on cookies. The session_start function creates a unique session ID and records it for future PHP processing tasks. The session ID is automatically stored in a cookie, or is maintained in the URL. Variable values are stored as part of the session data using session_register. The following script remembers the session for a couple of calls, then forgets everything.

session_start();
if (isSet($count)){
	echo "<h2>Welcome Back ($count)</h2>";
	if($count++>=2){session_destroy();}
}else{
	$count=0;
	session_register(count);
}