Back to DFS's PHP Page


Functions II -- An Include File

You will be creating many web pages while working with PHP. To save on typing and to make your code more readable (almost self-documenting at times), it is advantageous to store common HTML code fragments in functions which can be kept in a separate file. These can then be called upon when needed.

This programming technique requires the use of two files. The first is an HTML page which is either a static page or a dynamic one generated by a PHP script. This page transmits data back to the server where it is processed by a PHP script.

We will continue with the area-of-a-triangle problem for this demonstration.

N.B. For this code to work, make a copy of triform.html, calling the copy triformfunct.html. Change the line

to read


The Main Line Code

The following code should be saved in a file called triformfunct.php in ~/YOURID/public_html/. It will be executed when the user clicks on the "Calculate!" button in the form in a file called triformfunct.html (see below).

<?php
// triformfunct.php
// This script illustrates how to use functions kept in a separate file

// The triangle dimensions $b (base) and $h (height)
// are passed from triformfunct.html

// Specify file where functions are to be found
// The .inc suffix is short for "include"
require('htmlfuncts.inc');

pr_html_header("Calculating the Area of a Triangle: Result");
echo "<h1 align=\"center\">Calculating the Area of a Triangle: Result</h1>\n";
// Print the base
echo "<p>b is $b.\n";

// Print the height
echo "<p>h is $h.\n";

// Calculate and print result
$A = $b * $h / 2;
echo "<p>The area of a triangle with a base of $b and a height of $h is $A.\n";
pr_html_footer();
?>

Notes

The Functions Include File

The following code should be saved in a file called htmlfuncts.inc in ~/YOURID/public_html/.

<?php
// htmlfuncts.inc
// HTML functions
function pr_html_header($title) {
// Prints HTML header
// $title is title for title bar
   echo "<html>\n";
   echo "<head>\n";
   echo "<title>$title</title>\n";
   echo "</head>\n";
   echo "<body>\n";
}

function pr_html_footer() {
// Prints HTML footer
?>
</body>
</html>
<?php
}

Notes


© DFStermole: 2002
Created: 22 Sept 02
Last Modified: 22 Sept 02