This article explains how to build a simple calculator using PHP. We will create an HTML form to receive user inputs, perform calculations with PHP, and display the results to the user.
First, we need to create an HTML form where users can input two values to be calculated. Here's the code for the HTML form:
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form method="post" action="calculator.php">
<label>Enter the first number:</label>
<input type="number" name="num1">
<br>
<label>Enter the second number:</label>
<input type="number" name="num2">
<br>
<input type="submit" value="Calculate">
</form>
</body>
</html>
The above code creates a form with two input fields to accept user values and a submit button to trigger the calculation.
Next, we use PHP's global variable $_POST to receive the two values entered in the form:
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
This code stores the received values in the variables $num1 and $num2.
Now, we perform the addition of the two numbers using PHP:
$result = $num1 + $num2;
This code adds $num1 and $num2 and stores the result in the variable $result.
Finally, we display the calculated result to the user:
echo "Result: " . $result;
This line of code outputs the final result of the calculation.
Here’s the full PHP code for the calculator:
<?php
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$result = $num1 + $num2;
echo "Result: " . $result;
?>
In this article, we learned how to build a simple calculator using PHP. By combining an HTML form and PHP script, we can perform basic calculations. You can expand this calculator with additional functions, such as subtraction, multiplication, and division.
To ensure code security, it is recommended to validate and filter user inputs in real applications.