Back to DFS's Workshop Page
Back to Agenda Page
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 triformrequest.html, calling the copy triformfunctrequest.html. Change the line
<form method=\"POST\" action="triformrequest.php">to read
<form method=\"POST\" action="triformfunctrequest.php">
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 triformfunctrequest.html (see below).
<?php
// triformfunctrequest.php
// This script illustrates how to use functions kept in a separate file
// The triangle dimensions $b (base) and $h (height)
// are passed from triformfunctrequest.html
$b = $_REQUEST['b'];
$h = $_REQUEST['h'];
// 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();
?>
The line
require('htmlfuncts.inc');
serves to include at the point of call all code in the named file.
The file triformfunctrequest.html which sends the information to triformfunct.php is identical to triformrequest.html except for the "action" file specification.
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
}
?>
These functions illustrate two ways of writing function definitions which include HTML code. The first, pr_html_header, uses echo to output each line; the second, pr_html_footer, shifts out of PHP into HTML using ?> and then back into PHP using <?php to conclude the definition with the closing curly.