FIT3084: PHP : Hypertext Processor


In the previous lecture:

In this lecture:


References

Sebasta, R.W., "Programming the WWW 2009", 5th edition, Pearson, chapter 9.

http://www.php.net/


PHP logo

About

  • A server-side scripting language.
  • Often used for form handling and WWW database access.
  • An alternative to CGI, ASP, ASP.NET and JSP.
  • An Open Source project so we will discuss it rather than ASP and JSP.
  • The brainchild of Rasmus Lerdof (1994).
  • An acronym (originally) for Personal Home Page (tools) but now PHP: Hypertext Processor.
PHP data flow

How does PHP work?

  • PHP code is embedded in XHTML documents (like JavaScript)

  • PHP is interpretted by the server (unlike JavaScript... it is not seen by the client)

    • A server recognises a request for an XHTML document that contains PHP (often identified by file extension .php, .php3 or .phtml).
    • The PHP processor is called to interpret the code.
    • The processor sees XHTML (or JavaScript) in the file and copies it directly to the output file to send to the client.
    • The processor sees PHP in the file and executes it to create XHTML source or embedded client-side scripts and copies this to the output file to send to the client.
    • The result is always that XHTML (possibly with embedded client-side scripts) is sent back to the client that made the request. So...
    • If a surfer does "view source" on a page that contained PHP... they will not see the PHP source.

The PHP Language

PHP syntax is very similar to that of JavaScript and in some ways Perl. We shall only discuss it briefly...

Terminate PHP statements with a semicolon ;

Including PHP in an XHTML document

PHP comments

# Perl style comment
// C++ style single-line comment
/* and */ C style multi-line comment

PHP Variables

PHP basic types

Four scalar types:

  1. Boolean (TRUE and FALSE case insensitive)
  2. integer (actually a long integer)
  3. double
  4. string

Operators and expressions for numeric types

+ - * / % ++ -- = += /= etc. all work as expected.

Useful functions that operate on integers and doubles include:

floor( ) ceil( ) round( )
srand( ) rand( ) abs( )
min( ) max( )  
Consult http://au.php.net/manual/en/book.math.php for further details.

PHP string manipulation and printing

This 'string' and this "string" are both valid but...

The delimiters ' and ' ensure that embedded variables and escape sequences are not interpretted.

So assuming: $fred = 2; $tom=3; then

Source code Output
print 'The value $fred.\nThe value $tom.'; The value $fred.\nThe value $tom.
print "The value $fred.\nThe value $tom."; The value 2.
The value 3.
print "0.8 \$USD = 1.0 \$AUD"; 0.8 $USD = 1.0 $AUD

Operators and expressions for Strings

String concatenation: $beforeButterfly = "cat" . "er" . "pillar";

Accessing characters in a string: $beforeButterfly{2} has the value "t"

Useful functions for string manipulation include the usual ones and a lot more.

strlen( ) strcmp( ) strpos( )
substr( ) chop( ) trim( )
ltrim( ) strtolower( ) strtoupper( )
Consult http://au.php.net/manual/en/ref.strings.php for further details.

More PHP Output

The output from a PHP script must be XHTML or client-side script source code that will form part of the XHTML document containing the code.

print "This is a line of text<br /> and this is another.";

print "49"; and print(49); will both print out 49

print does not require the brackets ( and ).

printf("The value is %d", $fred);

printf( ) makes available all of the standard C printf( ) output formatting codes.

printf( ) requires the brackets ( and ).

PHP allows file I/O to files anywhere on the internet (and the server) using HTTP and FTP protocols. Consult (for example) http://au.php.net/manual/en/features.remote-files.php for details.


Control Structures

The relational and boolean operators >, <, >=, <=, !=, == all work as expected.

!, &&, || as well as and, or, xor are available too.
and and or have lower precedence than && and || but are otherwise the same.

=== is TRUE iff both operands are of the same type and exactly the same value (and conversely !== ).

If the types of operands compared using > < >= <= != == are not the same, one is coerced into the other's type. Be careful about this!

Selection and Iteration statements:

Selection (if)

Selection (switch)

Loop (while) Loop (for) Loop (do while)
if ( ... )
{ ... }
elseif ( ... )
{ ... }
else
{ ... }
switch ($variableName)
{
case "0":           
... break;
case "1": ... break;
default:
    ...
}
while ( ... )
{
 ...
}
for (...; ...; ...)
{
 ...
}
do
{
 ...
} while ( ... );

break and continue work as in C.


Sample PHP Script : Calculation

This computes the average of a random number of random values between 1 and 1000.

#!/usr/local/bin/php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Simple PHP Script</title>
</head>
<body>
<p>This is a simple page to display the result of a simple calculation performed in PHP.</p>
<p>
<?php
         srand(time());
         $numberOfValues = rand(1,100);
         $totalRatings = 0;
         for ($i=0; $i<$numberOfValues; $i++)
         {
             $total_ratings += rand(1,1000);
         }
         $average = $totalRatings / $numberOfValues;
         print("The average random value of $numberOfValues values between 1 and 1000 is: $average");
?>
</p>
</body>
</html>

Average random value script


PHP Arrays

PHP arrays are conventional non-negative integer-accessed arrays, hashes, or a mixture of both!

Array elements contain a value and a key.

The key may be a non-negative integer (standard array style ordered 0...n) or a string (hash style).

The values stored in an array may be of different types.

Creating and filling arrays

$myArray[0] = 21; If $myArray did not exist previously, this statement creates it and places 21 into the 0th element. If $myArray was a scalar variable before, this statement turns it into an array. Then...
$myArray[1] = "hello world"; This adds a new element and its corresponding string value hello world to $myArray
$myArray[ ] = 23; This adds a new element with the value 23 to $myArray in the cell location one after the last existing location (in this instance, it will have index 2 since 0 and 1 have been filled).

$myArray = array( ); This will create an empty array using the array( ) 'construct'.
$myArray = array(76, 91, 18, 23); This will also create an array containing the listed values into consecutive cells starting at cell 0.
$myArray = array(1=>76, 2=>91, 3=>18, 4=>23); This will do the same as above however values will be placed into the explicitly numbered cells from 1 to 4.
$myArrayScores = array("Alan"=>76, "Tom"=>54, "Mick"=>97); This creates an array in the form of a hash.
$myTree = array("species"=>"banksia", "aspect"=>"sunny", 3=>"rare", "height"=3); This creates an array that is partly a hash and partly a standard array.

Accessing array elements

$myArrayScores['Alan'] = 99; This will assign the value of 99 to the element with key Alan.

$trees = array("eucalyptus", "grevillea", "wattle");
list($tallTree, $shrub, $shortTree) = $trees;

The list( ) construct allows the assignment of a series of variables to consecutive elements of an array.
I.e. $tallTree = "eucalyptus", $shrub="grevillea", $shortTree="wattle".
$myArray = (76, 91, 18, 23);
unset($myArray[2]);
unset() will remove the specified element from this array, here leaving elements in locations 0, 1 and 3.

In your own time: Find out what the following array-related functions do:


explode( )
implode( )

array_push( )
array_pop( )
array_keys( )
array_values( )
array_key_exists( )

Sequential array access

$todayTemperature = $temperatureArray["Wednesday"];
print "Today's temperature will be $todayTemperature degrees.";
An array name embedded in " and " will not be evaluated by a print statement.
First assign the array value to a regular variable, then print it out.
$names = array("Alan", "Marco", "Mario", "MC Spandex");
$length = sizeof($names");
To determine the size of an array use sizeof(). In this example, $length will be 4.

$ageArray = array("Alan"=>30, "Marco"=>33, "Mario"=>31, "MC Spandex"=>27);
       
while($rider = each ($ageArray))
{
   $name = $rider["key"];
   $age = $rider["value"];
   print("The age of $name is $age <br />");
}

To iterate through an array's elements one at a time use the each() function. This returns a two-element array containing the key/value pair associated with each element. each() returns FALSE if there are no more elements in the array.

In your own time: Research the next(), prev() and current() functions to give you a complete understanding of how to iterate through PHP arrays.
foreach ($ageArray as $age)
{
print ("$age <br />");
}
The foreach( ) loop can be used simply to access each value in turn as a scalar variable.
foreach ($ageArray as $name => $age)
{
   print("The age of $name is $age <br />");
}
The foreach( ) loop can also be used in a different form to access each key/value pair.

PHP Functions

function name ([optional parameters])
{ ... }

A PHP function definition looks like a Javascript function.

Functions may (or may not) return a value using the return statement.

function capValue( &$valueToCap )
{
if ($valueToCap > 100)
{ $valueToCap = 100; }
}

Standard parameter passing is pass by value.

To pass by reference add an ampersand & to the function declaration of the formal parameter.
Or you can place an & before the actual parameter in the function call to get the same effect.

In your own time: Research the global and static reserved words to see how to access global and static variables from within a function.


Sample PHP Script : Form Handling

Super Stardom

This XHTML form is specified here with the tag:

<form action="cgi-bin/lectPHPSuperstarScript.cgi" method="post"
name="superstar" id="superstar">

Here is the <body> of lectPHPSuperstarScript.cgi

<body>
<h2>Official Certificate of Super Stardom</h2>
<p>By the authority vested in me, the lecturer, I hereby declare that
<?php
       $givenName = $_POST["givenName"];
       $familyName = $_POST["familyName"];
       print " $givenName $familyName is";
if ($_POST["superstarBox"] == FALSE)
{ print " <strong>not</strong>"; }
print " a superstar. <br />";
print "In addition, it is hereby officially recognised that";
if ($_POST["gender"] == male)
{ 	$pronoun = "he"; $possessivePronoun = "his"; }
       
else
{  $pronoun = "she"; $possessivePronoun = "her"; }
       
switch($_POST["loveHate"])
{
       case "love": $who = "everybody"; break;
       case "hate": $who = "nobody"; break;
       default: $who = "only $possessivePronoun Mum";
}
   
print " $pronoun is a person whom $who loves."
?>
</p>
<p>Signed, <br /> The Lecturer.</p>
</body>

....Phew! There is still more to know about PHP but that just about covers the basics.



This lecture's key point(s):


Courseware | Lecture notes

©Copyright Alan Dorin 2009