Back to DFS's PHP Page


Getting Data from a Form

Instead of just getting data from a file, PHP allow you to receive data from an HTML form as well. This capability is one of the reasons that PHP is so popular for web programming.

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 return to the area-of-a-triangle problem for this demonstration.

N.B. For this code to work your web server must be running.

A Static HTML Page with a Form

The creation of an HTML form is well described on the Coding Forms page at 2K Communications and on the Forms Tutorials page at HTML Goodies.

The following code should be saved in a file called triform.html in ~/YOURID/public_html/.

<!-- triform.html -- calls triform.php from form 
     passing b and h -->
<html>
<head>
<title>Calculating the area of a triangle</title>
</head>
<body>
<p><a HREF=index.html>Back to DFS's PHP Page</a></p>
<hr>
<h1 align=\"center\">Calculating the Area of a Triangle</h1>
<p>Enter the dimensions of a triangle and click on "Calculate!" to have a PHP script calculate its area.</p>
<form method=\"POST\" action="triform.php">
<table border>
<tr>
 <td>Base</td><td><input type="text" name="b" value="" size="5"></td>
</tr>
<tr>
 <td>Height</td><td><input type="text" name="h" value="" size="5"></td>
</tr>
<tr>
 <td colspan="2" align=center><input type="submit" value="Calculate!"><input type="reset"></td>
</tr>
</table>
</form>
</body>
</html>

A PHP Script to Handle the Information from the Form

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

<!-- triform.php -->
<html>
<head>
<title>Calculating the Area of a Triangle: Result</title>
</head>
<body>
<?php
// This script illustrates how to process information
// sent from a form on a web page

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

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";
?>
</body>
</html>

Notes


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