Sie sind auf Seite 1von 3

PHP Example Programs

Dr. Paul Walcott


03/11/05

In this document a number of PHP programs have been provided to introduce the reader to the
PHP language.

The calculator example requires two files, Calculator.html and Calculator.php.

This program accepts two numbers and:


1. Adds the first number to the second
2. Subtracts the first number from the second number
3. Multiplies the first number by the second number
4. Divides the first number by the second number

Calculator.html

<html>

<head>
<title>Calculator</title>
</head>

<body>

<form action="calculator.php" method="post">

Input 1:<input type="text" name="i1" value="2"><br>


Input 2:<input type="text" name="i2" value="1"><br>
<br>
<input type="submit" value="Add" name="Add">
<input type="submit" value="Subtract" name="Subtract">
<input type="submit" value="Multiply" name="Multiply">
<input type="submit" value="Divide" name="Divide">

</form>
</body>
</html>
Calculator.php

<html>
<head>
<title>Calculator-Results</title>
</head>

<body>

<?php
// Simple Calculator Program
// Author: Paul Walcott 02/11/05
//
// This program adds, subtracts, multiplies or divides two
// numbers that has been submitted from the form in the
// file calc.html
//
// This program has not been written for efficiency,
// it merely serves
// as an example of the use of PHP program structures

// get the values input by the user on the form

$input1 = $_REQUEST['i1'];
$input2 = $_REQUEST['i2'];
$add = $_REQUEST['Add'];
$subtract = $_REQUEST['Subtract'];
$multiply = $_REQUEST['Multiply'];
$divide = $_REQUEST['Divide'];

// has the user clicked on the Add button?

if ($add == "Add")
{
// no validation is being done here

// Add the numbers


$result = $input1 + $input2;

// Output the results


print ($input1 . " + " . $input2 . " = " . $result);
}
else if ($subtract == "Subtract")
{
// no validation is being done here

$result = $input1 - $input2;


print ($input1 . " - " . $input2 . " = " . $result);
}
else if ($multiply == "Multiply")
{
// no validation is being done here

$result = $input1 * $input2;


print ($input1 . " * " . $input2 . " = " . $result);
}
else if ($divide == "Divide")
{
// no validation is being done here

$result = $input1 / $input2;


print ($input1 . " / " . $input2 . " = " . $result);
}

// output all the text between the print statement and "END"

print <<< END


<br>
<br>
<a href="calculator.html">Return to calculator</a>

END;

?>

</body>
</html>