Skip to content The Open University

TT284 Insight - PHP


This material is largely taken from part Part 4 of Block2 starting at the point when the PHP language is introduced.

5 PHP and HTML

Earlier in this block you saw how JavaScript can be embedded into HTML pages as well as two different types of functionality this can support:
  • accessing page elements using the Document Object Model (DOM) and specifically how values typed into form fields can be accessed so that they can be validated;
  • altering the composition of the web page using the DOM, for example to add a message to the web page when validation fails.
PHP resides on the server. So, when a request is made for a page the server will fetch the page and execute any PHP scripts before sending the resulting content of the page back to the user as an HTTP response.

The server-side operation of PHP means that scripts are typically used to produce the content of the web page itself as well as any other work that needs to be done, such as accessing information in a database. So, the PHP equivalent of JavaScript’s ‘document.write’ is very common.

Activity 4 Introducing PHP

Before we look at some examples of script, read the brief introduction to PHP provided by John Coggeshall’s (2001a) guide to ‘Basic PHP syntax’.

Coggeshall’s (2001a) guide provides a very short introduction to how PHP is embedded in HTML and also introduces basic variables in PHP.

To ensure you understand how to embed PHP in a web page, you could try out some of the sample scripts you have seen, on your own software platform if you have set one up or using your OU server account on the TT284 server. If you are not confident to do this now, you will learn how to do it in Activity 5.

5.1 Code and scripts

5.1.1 Commenting code
Commenting your code means that it is easier to maintain and read, both for yourself and for others who may need to modify your code later. Comments also allow you to leave yourself reminders of why you have implemented something in a particular way. Commenting also provides a mechanism to help with the debugging process by allowing chunks of code to be selectively made ‘invisible’. So you might include code to write out messages about the values being manipulated for debugging purposes, but which you later remove by commenting the message code out when the actual program code is working as you desire.

Just as HTML comments, which are contained within special tags, are ignored by the web browser, the PHP parser recognises and ignores PHP comments in any of the three following styles:

        // This is a basic one-line PHP comment
        /* This is a C-style PHP comment that can span multiple lines. */
        # This is a "shell-style" PHP one-line comment

The ‘C-style’ comment has the same format as a comment in the C programming language and the ‘shell-style’ comment has the format of a Linux or Unix comment in a shell script. The names are not important here, just that you have the option to use whichever style you prefer. Most PHP scripts you encounter will use a combination of the first two.

It is important to realise that comments are only useful if they are clearly written. Incorrect or misleading comments are not helpful. Comments also need to be maintained, such as updating whenever the code they document is changed.

5.1.2 Starting with PHP scripts
In this module we will focus on the PHP required to operate a small web application that receives and stores data sent from a validating form. The stored data can then be retrieved by another PHP page and sent to the user on request. I will not consider here revalidating data on the server using PHP, although it should become a simple matter to extend the work to accomplish this.

We will be moving on to examine how to process and store the form’s data. You should become familiar with how PHP is embedded in an HTML page and how it is processed to produce additional ‘dynamic’ parts of a an HTML page.

Activity 5 PHP Hello World

First I will demonstrate how to write a simple script in PHP that will print out ‘Hello World from PHP’ to the browser. The PHP statement to dynamically print ‘Hello World from PHP’ is:

echo 'Hello World from PHP';

First here is an HTML file which will serve as the starting point for the PHP file:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>Hello World</title>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    </head>
    <body> <h1>Hello World: My First PHP Program</h1> </body>
    </html>

Taking this file as a starting point the steps to producing and running it with the addition of PHP statements are:
  • add the PHP script to the file. In this case I will add a single 'echo' statement which can replace the heading in the HTML body. This code is enclosed by PHP start ('<?php') and PHP end ('?>') tags:

        <?php echo "Hello world from PHP"; ?>

  • The file then has to be renamed or saved to a file with a '.php' extension (rather then '.html')
  • then, of course, the file needs to be uploaded to a server which has the ability to execute PHP code
  • and, lastly the file has to be requested by a user who loads its URL into a browser.
You can find the adjusted PHP file in the Block 2 Part 4 Resources which you can download. Then upload this PHP file to your TT284 server account and display the file in your browser.

Then edit the PHP file so that it writes out your name and OUCU and upload it again to your server account. Note that uploading a file with the same name as one already on the server will overwrite the file on the server.

If you encounter difficulties, post your sample PHP script and a description of your problem in the practical activities forum.

6 Using PHP arrays

Now you have seen how to output ‘Hello World’ using echo, you should be able to write a script to generate an HTML table. I will step through how to go about this. Suppose we want to produce a page which contains the table shown below.
NameTime
N. Heap1.20.32
K. Kear1.10.09
J. Jones1.30.07
This is a simple table of runners’ names and their time taken to complete a certain run. Ordinarily the data in the table (names and times) would be stored in a database but for now let’s create a PHP array that holds this data. Here’s an array which would hold the times:

   $times = array("1.20.32", "1.10.09", "1.30.07");

This array has three elements which are implicitly number 0, 1 and 2. In PHP the array elements can be accessed using:

   $times[0]; $times[1]; times[2];

In PHP each array element can be given a ‘key’, which is an integer or a string, so the $times array could equally be declared:

   $times = array( 0 => "1.20.32", 1 => "1.10.09", 2 => "1.30.07" );

Each time in the array now has an explicit key (‘0’, ‘1’, ‘2’) but as keys can also be strings, we can set up an array of times where the keys are the names of the runners:

   $times = array(
     "N. Heap" => "1.20.32",
     "K. Kear" => "1.10.09",
     "J. Jones" => "1.30.07"
    );

Now, the array can be accessed using a name as a key, for example:

   $times[‘N. Heap’];

The usual approach to processing an array is to use a loop. In PHP there are several forms of loop (e.g. for, while, etc., (PHP, 2012b)). A very commonly used loop is the ‘foreach’ loop which provides access to each value in an array sequentially:

   foreach (array_expression as $value) 'some PHP statement'

It can also be used to access both the key and the value of each element in an array:

   foreach (array_expression as $key => $value) 'some PHP statement'

Using ‘foreach’ the $times array (keys and values) can be accessed and written out as part of an HTML table:

   // output table tag and header row first:
   echo '<table border=1><tr><th>Field</th><th>Value</th></tr>';
   // for each array element write the key and value as table data:
   foreach ($times as $name => $time)
   {
     echo '<tr><td>';
     echo htmlspecialchars(print_r($name, true));
     echo '</td><td>';
     echo htmlspecialchars(print_r($time, true));
     echo '</td></tr>';
   }
   echo '</table>';

The ‘htmlspecialchars’ function (PHP, 2012c) translates any special characters, such as ‘&’, into their HTML representation for example ,’&’. The ‘print_r’ function prints out the value of a variable in a human readable fashion. The second ‘true’ argument indicates that the function should return a value, for ‘htmlspecialchars’ to handle rather than print the value out itself directly.

Activity 6 Print table

Write PHP to print the following table into an HTML web page:
NameOccupation
K SmithPlumber
N JonesElectrician
P IbbotsonPlasterer
Base the table on a PHP array:

    $employment = array(
         "K Smith" => "Plumber",
         "N Jones" => "Electrician",
         "P. Ibbotson" => "Plasterer"
    );

If you want to know more about PHP than required for Block 2, you can find out about other functions and the function reference in the PHP manual (PHP, 2012d) Arrays and their built-in PHP functions are also documented on the PHP site (PHP, 2012e).

Activity 7 Sorting

Modify your ‘Print table’ code to produce the employment table by trying out Array functions for sorting an array. Sort the array using say ‘asort’:

asort($employment);

The asort function sorts an array based on the values found and maintains the associated key values. If you try out ‘sort’ you will find that it reassigns the keys (0, 1, etc.) and so the original keys are lost.

Activity 8 Further PHP functions and reference resources

So far I have used a small number of PHP functions to print out some values as HTML. The functions required for Block 2 are discussed in the Block guides but PHP has a far wider range of functions and you should make sure you are able to look these up and find functions that are suitable for your wider needs.

Visit the excellent PHP website (PHP, 2012a) and browse the site to see what’s available. Read John Coggeshall’s (2001b) ‘An introduction to PHP’ as well as the ‘Introduction’ on the PHP (2012) website.

Note that there is an extensive ‘PHP Manual’ for reference on the PHP website and a ‘PHP Tutorial’ on the w3schools website (www3schools, 2012), which will be a useful resource throughout the remainder of this block. You can download an up-to-date version from the website.

There are also websites with various other resources, like tutorials, articles, or even podcasts. For example the PHP Builder (2012) and the Zend Developer Zone (2011) websites.

References

Coggeshall, J. (2001a) ‘Basic PHP syntax’, available at http://www.onlamp.com/pub/a/php/2001/03/08/php_foundations.html [accessed 2 February 2012].

Coggeshall, J. (2001b) ‘An introduction to PHP’, available at http://onlamp.com/pub/a/php/2001/02/22/php_foundations.html [accessed 02 February 2012].

IIS (2011), available at http://www.iis.net/ [accessed 02 February 2012].

MSDN Microsoft (2012) ‘Overview of the .NET framework’, available at http://msdn.microsoft.com/en-us/library/zw4w595w(v=vs.71).aspx [accessed 02 February 2012].

MSDN Microsoft (2012) ‘ASP.NET overview’, available at http://msdn.microsoft.com/en-us/library/4w3ex9c2.aspx [accessed 02 February 2012].

Oracle (2012) ‘Why MySQL’ available at http://www.mysql.com/why-mysql/ [accessed 02 February 2012].

Oracle (n.d.) Java, available at http://www.oracle.com/us/technologies/java/index.html [accessed 02 February 2012].

Perl (2012) The Perl Programming Language, available at http://www.perl.org/ [accessed 02 February 2012].

PHP (2012a) ‘PHP manual’, available at http://www.php.net/manual/en/index.php [accessed 02 February 2012].

PHP (2012b) ‘Control structures’, available at http://www.php.net/manual/en/language.control-structures.php [accessed 02 February 2012].

PHP (2012c) ‘htmlspecialchars’ available at http://www.php.net/manual/en/function.htmlspecialchars.php [accessed 02 February 2012].

PHP (2012d) ‘Function reference’, available at http://www.php.net/manual/en/funcref.php [accessed 02 February 2012].

PHP (2012e) ‘Arrays’, available at http://www.php.net/manual/en/book.array.php [accessed 02 February 2012].

PHP (2012f) ‘Include ()’ available at http://www.php.net/manual/en/function.include.php [accessed 02 February 2012].

PHP (2012g) ‘Superglobals’ available at http://www.php.net/manual/en/language.variables.superglobals.php [accessed 02 February 2012].

PHP Builder (2012), available at http://phpbuilder.com/ [accessed 02 February 2012].

Python (2011) Python Programming Language, available at http://python.org [accessed 02 February 2012].

The Apache Software Foundation (2012a) Apache Tomcat, available at http://tomcat.apache.org/ [accessed 02 February 2012].

The Apache Software Foundation (2012b) ‘Apache: HTTP server project’, available at http://httpd.apache.org/ [accessed 02 February 2012].

TIOBE Software (2012) ‘TIOBE Programming Community Index for January 2012’, available at http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html [accessed 02 February 2012].

w3schools (2012) ‘PHP tutorial’ available at http://www.w3schools.com/php/default.asp [accessed 02 February 2012].

Zend Developer Zone (2011) available at http://devzone.zend.com/ [accessed 02 February 2012].