Mostrando postagens com marcador PHP Forms. Mostrar todas as postagens
Mostrando postagens com marcador PHP Forms. Mostrar todas as postagens

How to Build a Simple PHP Calculator (With Line-by-Line Code Explanation)

Progressive PHP Full Course

⚙️ Your First Interactive PHP Project

In our previous modules, we learned about PHP Math Operators and Handling User Input. Today, we are going to combine these two fundamental concepts to build something real: a functional PHP Calculator. Instead of just giving you the final code, we will explain exactly how the frontend and backend talk to each other.

Explore the Full PHP Syllabus →

The Goal: Building a PHP Arithmetic Calculator

"Write a PHP script that receives two numbers from a user via an HTML form and calculates: the sum, the difference, the product, the quotient (division), and the remainder (modulo)."

Step-by-Step Code Explanation

To build this application properly, we need to understand the three distinct layers of our software. Let's break down the logic before looking at the final file.

1. The HTML Form (The Interface)

First, we need a way for the user to type their numbers. We use standard HTML for this.

<form action="home.php" method="GET">
    <input type="number" name="num1" step="any" required>
    <input type="number" name="num2" step="any" required>
    <input type="submit" value="Calculate">
</form>
  • action="home.php": This tells the browser to send the typed data to our PHP file named home.php.
  • method="GET": This sends the data through the URL, which is perfect for a simple calculator.
  • type="number" and step="any": This is a great UX (User Experience) practice. It forces the browser to only accept numbers (including decimals), preventing users from typing letters.

2. Capturing Data Securely (The Backend Bridge)

Once the user clicks "Calculate", PHP takes over. But what happens if the user visits the page for the very first time, before submitting any form? PHP would try to calculate numbers that don't exist yet, causing an error!

if(isset($_GET['num1']) && isset($_GET['num2'])) {
    $num1 = (float)$_GET['num1'];
    $num2 = (float)$_GET['num2'];
}
  • isset(): This is a built-in PHP function. It translates to: "Does this data exist?" We use it to wrap our logic so the math only happens IF the user actually submitted the form.
  • (float): This is called Type Casting. Even though the HTML field is a "number", everything sent via HTTP is technically text. By placing (float) before our variable, we forcefully convert the text into a decimal number, making our application much safer against malicious inputs.

3. Processing and Concatenating Data

Now that we have safe, clean numbers stored in $num1 and $num2, we need to do the math and display it.

echo "Addition: " . ($num1 + $num2) . "<br>";
  • The Dot (.): In PHP, the dot is used to glue (concatenate) strings and variables together.
  • Parentheses ($num1 + $num2): These are mandatory! They tell the PHP engine: "Hey, do the mathematical calculation inside these brackets first, and only then attach the result to the word 'Addition'."

The Complete Source Code (home.php)

Now that you understand the mechanics, create a file named home.php in your local server and paste the complete code below to see it in action.

<!DOCTYPE html>
<html>
<head>
    <title>My PHP Calculator</title>
</head>
<body style="font-family: Arial, sans-serif; margin: 40px;">

    <h2>PHP Math Calculator</h2>
    
    <form action="home.php" method="GET">
        <label>Number 1:</label>
        <input type="number" name="num1" step="any" required><br><br>
        
        <label>Number 2:</label>
        <input type="number" name="num2" step="any" required><br><br>
        
        <input type="submit" value="Calculate" style="padding: 10px 20px; cursor: pointer;">
    </form>
    
    <hr style="margin: 30px 0;">

    <?php 
        // Ensure the form was submitted
        if(isset($_GET['num1']) && isset($_GET['num2'])) {
            
            // Capture and sanitize inputs
            $num1 = (float)$_GET['num1'];
            $num2 = (float)$_GET['num2'];
            
            echo "<h3>Results:</h3>";
            
            // Output calculations
            echo "Addition: " . ($num1 + $num2) . "<br>";
            echo "Subtraction: " . ($num1 - $num2) . "<br>";
            echo "Multiplication: " . ($num1 * $num2) . "<br>";
            
            // Prevent Division by Zero Error
            if($num2 != 0) {
                echo "Division: " . ($num1 / $num2) . "<br>";
                echo "Modulo (Remainder): " . ($num1 % $num2) . "<br>";
            } else {
                echo "<span style='color: red; font-weight: bold;'>Error: You cannot divide by zero!</span><br>";
            }
        }
    ?>

</body>
</html>

💡 Expert Tip: Anticipate Errors (Division by Zero)

A good programmer doesn't just write code that works; they write code that doesn't break. In mathematics, dividing a number by zero is impossible. If a user types 0 in the second field and your PHP script tries to divide by it, PHP 8+ will throw a Fatal Error: Uncaught DivisionByZeroError and crash your entire application. That is why we wrapped the division block inside an if($num2 != 0) safety check!

Did you get your calculator running? Challenge: Try adding a third input field to calculate the average of three numbers! Post your updated code in the comments below.


Next Step: Controlling the Flow

You've just built an app that makes a decision (checking if the divisor is zero). This is called conditional logic. In the next module, we will dive deep into PHP If, Else, and Elseif Statements to give your applications true artificial intelligence!

Go to the Next Lesson in the Syllabus →

How to Handle HTML Forms and User Input in PHP ($_GET & $_POST)

The Concept of User Input in Web Development

Think about the actions you perform on the internet every single day:

  • When you type your username and password, the server checks those credentials and grants you access. If they are wrong, it returns an error message.
  • When you search for a product on Amazon, the website reads your search query and returns only the relevant database results.
  • When you try to transfer money, the banking system checks if your input amount is lower than your current balance before approving the transaction.

All of these scenarios rely on a fundamental concept: Client-Server Communication. The Client (your web browser) collects data from the user and sends it to the Server. The Server (running PHP) catches this data, processes it according to your business logic, and sends back a response.

Today, we are going to learn how to build that bridge.

Step 1: Creating the HTML Form

Everything starts on the frontend. To send data to PHP, we need an HTML <form>. The form tag has two crucial attributes you must memorize:

  • action: Tells the browser where to send the data (e.g., "process.php").
  • method: Tells the browser how to send the data (usually "GET" or "POST").
<!-- The HTML Form -->
<form action="home.php" method="GET">
    <label for="username">Enter your name:</label>
    <!-- The 'name' attribute is EXTREMELY important. PHP uses it as the key. -->
    <input type="text" id="username" name="user_name" required>
    
    <input type="submit" value="Send Data">
</form>

Step 2: Capturing Data with PHP Superglobals

Once the user clicks "Send Data", PHP wakes up. To grab the information, PHP uses built-in variables called Superglobals. These are special Arrays that are always available in all scopes throughout your script.

Because our form used method="GET", PHP will automatically store the typed data inside the $_GET superglobal array. To retrieve it, we use the name attribute we defined in the HTML input (which was user_name).

<?php 
    // This is how PHP captures the data
    $captured_name = $_GET["user_name"];
    
    echo "Welcome to the system, " . $captured_name;
?>

The Complete Working Example

Let's put both the HTML and the PHP in the same file (let's call it home.php). We will also add a critical safety check using the isset() function. This prevents PHP from throwing an error when you visit the page for the first time (before the form is submitted).

<!DOCTYPE html>
<html>
<head>
    <title>PHP Form Tutorial</title>
</head>
<body>

    <h2>Test out PHP Input!</h2>
    <form action="home.php" method="GET">
        <label>Type something:</label>
        <input type="text" name="my_input">
        <input type="submit" value="Send to PHP">
    </form>
    
    <hr>

    <?php 
        // Check if the form was actually submitted
        if (isset($_GET["my_input"])) {
            // It's good practice to sanitize data (prevent XSS hacks)
            $safe_data = htmlspecialchars($_GET["my_input"]);
            echo "<h3>PHP Received: " . $safe_data . "</h3>";
        }
    ?>

</body>
</html>

Understanding GET vs. POST

You might be wondering: what happens if I change the form method to POST? How does PHP handle it?

  • The GET Method: When you use GET, the browser appends the form data directly into the URL (e.g., home.php?my_input=Hello). This is fantastic for search bars or filtering products because users can bookmark or share the URL. However, never use GET for passwords, as everyone can see the data in the address bar.
  • The POST Method: When you use POST, the data is sent invisibly within the HTTP request body. The URL remains clean (e.g., home.php). This is mandatory for login forms, credit card checkouts, and sending large amounts of text. To capture it, you simply change your PHP code to use $_POST["my_input"].

🚧 Common Error: "Undefined array key"

If you get a warning saying "Warning: Undefined array key 'my_input'", it means PHP tried to read the data before the user clicked the submit button, OR you made a typo in the HTML name attribute. Always wrap your capturing logic inside an if (isset($_GET['...'])) block to ensure the data actually exists!

Were you able to make PHP repeat your text? Try adding a second input field (like "Age") and printing both values! Drop your code in the comments below.


Next Step: Making Decisions

Now that you can capture user input, we need to teach our application how to make choices based on that data. In the next tutorial, we will dive into PHP IF/ELSE Statements (Conditional Logic) to build our very first login verification system.

Go to the Next Lesson in the Syllabus →