Software Technologies for the Web
 

PHP

What is PHP

PHP is a client side programming language, PHP means PHP Hypertext Preprocessor. You can embed it into your HTML, or vice versa. It was developed by Rasmus Lerdorf in 1995, back then it stood for Personal Home Page.
It has now become one of the most popular modules that are added to to the Apache web server, as of April 2007 it was available on 20,917,850 domains (Netcraft 2008).

 

PHP Examples

PHP comes with many functions built into it. These range from outputting system information to sending e-mails.
This next section will look at some of these functions, showing examples of how to use them.

Licence Information

You can output a file to the screen displaying the configuration of the version of PHP you are working with. This is performed by using the phpinfo( ) function.
When using this function you can pass it a parameter to only display certain information. These parameters are as follows;

Name (constant)ValueDescription
INFO_GENERAL1The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS2PHP Credits. See also phpcredits().
INFO_CONFIGURATION4Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES8Loaded modules and their respective settings. See also get_loaded_extensions().
INFO_ENVIRONMENT16Environment Variable information that's also available in $_ENV.
INFO_VARIABLES32Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE64PHP License information. See also the » license FAQ.
INFO_ALL-1Shows all of the above. This is the default value.

(PHP.net 2008)


This example will extract only the licence information, to do this we will have to pass the parameter of 64.
This code would look as follows;

<?php
phpinfo(64);
?>

When this is executed it gives the following output; Output of phpinfo

See this working.
Source code is here.

Tomorrows Date

PHP is bundled with many functions that can manipulate dates and time. This example uses the mktime and date functions to show tomorrows date.
mktime creates a timestamp from a given set of parameters passed to it. The order in which they are passed is important, they have to follow a set format as follows;

  1. Hour
  2. Minute
  3. Second
  4. Month
  5. Day
  6. Year

The timestamp is a integer value that is counts from January 1st 1970 (this is known as UNIX Epoch time).
You can use the date function to format the output of mktime. This will format the date as per the parameters passed to it. A full list of these can be found at PHP.net

<?php
$tm = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));
$tomorrowDate = date("l jS F, Y", $tm);
echo "Tomorrows date will be ".$tomorrowDate;
?>

This gives the ouput;
Tomorrows date will be Thursday 9th September, 2010

See this working.
Source code is here.

Working with Forms

You can use PHP to process forms, giving you the ability to create dynamic content for your web pages. This is performed by using the special super global variables $_GET and $_POST. Which one you use depends on the method used to send the form.
In the next example we will use the $_GET variable, as the form that is passing data uses the get method.
First we need to create the form. We will ask the user for their favourite book and meal;

<html>
<body>
<form action="form2.php" method="get">
Favourite book: <input type="text" name="book" />
Favourite meal: <input type="text" name="meal" />
<input type="submit" />
</form>
</body>
</html>

Now we have our form, we need to write the php script to process it. The script needs to get the form data (via the query-string). There are a couple of options for processing the query-string. This example will access the data directly through an array. This method works by storing each bit of data into an hash array element defined by its name value in the form.

<html>
<body>
Welcome, your favourite book is: <?php echo $_GET["book"]; ?>.
And your favourite meal is: <?php echo $_GET["meal"]; ?>
</body>
</html>

See this working.
Source code for form is here,
and source code for result page is here.

Back to top
 

Templating

Advantages of a Template System

When designing a a large web site you could code each and every page individually. This would be time consuming, and errors could creep in. With PHP you can streamline this with the use of templates. These allow you to separate your pages into logical blocks and call them into a page. This is performed by using the include and require functions. These functions let you import other files into the current page. An example of a simple template system can be found below
The main advantages associated with using templates is similar to that regarding any type of modular design. It creates blocks of reusable code that can be included into many pages. this itself has the advantage when it comes to editing. By using a template system if you edit one file it can effect the whole site.

Disadvantages of a Template System

The disadvantages of templates can often be user induced. If a script makes excessive calls to include other files it may have a negative effect on load times. Many users won't wait longer than eight seconds for a web page (King 2008).
From a developers point of view it can make the code difficult to read and not very semantically rich. This could cause problems when the job of site maintenance passes over to someone new.

Template Engines

Rather then using include and require, you could use one of the many template engines available. Some of the most well known are Smarty and patTemplate. While the theory of these may be good, the practice is often not. For none technical people the user manuals can be difficult to follow. They can also use markup that many developers are unfamiliar with, example Smarty uses { } (braces), not < >. Using these tags can also cause problems for the web server. If an error occurs in the parsing of the file it will print the { } tags, revealing the code to the users. PHP tags (which use the < notation) will be hidden from the browser as it will try an interpret it as an HTML tag (phpPatterns 2008).

Template Example

We will now show an example of how to create a template system site. This example will use this site as an example.

1. As you can see when viewing this site, certain elements are always the same. The top region (site name and logo) appear on all pages, as does the bottom region. Rather then code this into every page we will separate them into individual pages.
We now have two pages;

2. Now we need to create our index page. The secret behind this is processing the query string that will be coded into every page.
Lets take a look at the code and then we will break it down;

<?php
include "include/templates/header.php";
if ($_GET['unit'])
{
$unit_selection = $_GET['unit'];

switch ($unit_selection)
{
case 1:
$pageContent = "unit1.php";
break;
case 2:
$pageContent = "unit2.php";
break;
case 3:
$pageContent = "unit3.php";
break;
case 4:
$pageContent = "unit4.php";
break;
case 5:
$pageContent = "unit5.php";
break;
case 6:
$pageContent = "unit6.php";
break;
default:
$pageContent = "home.php";
break;
}
}
else
{
$pageContent = "home.php";
}

include $pageContent;
include "include/templates/footer.php";
?>

You will notice that we start by using the include function to import the header file.

include "include/templates/header.php";

We then test (by using an IF statement) if any data is being passed to the page by means of the GET method of the query string.
If this test fails we load a default set of content (in this case the index page material).

// testing for variable called unit
if ($_GET['unit'])
{
     .....
} // if test fails
{
// load content for index page
$pageContent = "home.php";
}

Being good programmers we need to perform a task.
We transfer the value held in the GET variable into another variable with a more meaningful name.

$unit_selection = $_GET['unit'];

If there is a value in the GET[unit] variable we need to process it so that we can load the right data. We do this by using a special multiple IF statement called a SWITCH.
This compares the value being tested against the various cases.
N.B Remember the unit_selection variable holds an integer value, SWITCH statements will only work with either an integer or single character input.

switch ($unit_selection)
{
case 1: // do this if unit_selection is 1
$pageContent = "unit1.php";
// store unit1.php into variable
break; // exit switch statement
case 2:
$pageContent = "unit2.php";
break;
.....

If none satisfy any of the cases, a default option is run.
In this example that is to load the index page material.

...
default:
$pageContent = "home.php";
break;

Once we know what content we want, we can import that file (stored in the variable $pageContent).

include $pageContent;

And finish by adding the footer file we created earlier.

include "include/templates/footer.php";

[view index file]

3. All that is left to do now is to create the files containing the content for each page. Care must be taken regarding the HTML tags, as you are effectively carrying on from the header file. My tip for this is to create a template file that you can edit, then save with the name you wanted.
So you can see an example, we will code the home.php file which holds the data for the index page.
The main part to remember is the coding of the navigation bar. This is what drives the template system. Rather then write code for each link, we can use a loop to do it for us.

<h1>Unit List</h1>
<ul>
<?php
for ($i = 1; $i <= 6; $i++)
{
print"<li><a href=\"index.php?unit=$i\">
         Unit $i</a></li>\n";
}
?>
</ul>

Notice that the query-string and its value have been hard-coded into the link. This guides us back to the index page for processing.

<a href=\"index.php?unit=$i\">

Now we have all the files in place to create a large site that can be maintained easily.
[view home file]
[View all files](Beware, this opens several new tabs/windows).

Back to top

References

Back to top