DEV Community

Cover image for PHP crash course: Simple Calculator
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

PHP crash course: Simple Calculator

Simple Calculator

Create a basic calculator that can perform addition, subtraction, multiplication, and division.

Creating a basic calculator with PHP, CSS, and AJAX involves a few key components:

  1. Frontend (HTML + CSS + JavaScript/AJAX): This handles the user interface and interactions.
  2. Backend (PHP): This handles the calculation logic and returns the results.

1. Frontend: HTML + CSS + JavaScript/AJAX

HTML (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled>
        <div class="buttons">
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('+')">+</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('-')">-</button>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('*')">*</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="calculate()">=</button>
            <button onclick="appendToDisplay('/')">/</button>
            <button onclick="clearDisplay()">C</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS (styles.css):

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
}

.calculator {
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-color: #fff;
    padding: 10px;
    width: 200px;
}

#display {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    text-align: right;
    font-size: 24px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 3px;
}

.buttons button {
    width: 45px;
    height: 45px;
    font-size: 18px;
    margin: 2px;
    border: 1px solid #ccc;
    border-radius: 3px;
    background-color: #f9f9f9;
    cursor: pointer;
}

.buttons button:hover {
    background-color: #e0e0e0;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript (script.js):

function appendToDisplay(value) {
    document.getElementById('display').value += value;
}

function clearDisplay() {
    document.getElementById('display').value = '';
}

function calculate() {
    var display = document.getElementById('display');
    var expression = display.value;

    if (expression) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'calculate.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function () {
            if (xhr.status === 200) {
                display.value = xhr.responseText;
            }
        };
        xhr.send('expression=' + encodeURIComponent(expression));
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Backend: PHP

PHP (calculate.php):

<?php
if (isset($_POST['expression'])) {
    $expression = $_POST['expression'];

    // Remove any potential security risks
    $expression = preg_replace('/[^0-9+\-.*\/()]/', '', $expression);

    try {
        // Evaluate the expression
        $result = eval('return ' . $expression . ';');
        echo $result;
    } catch (Exception $e) {
        echo 'Error: Invalid expression';
    }
}
?>
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Frontend (HTML + CSS + JavaScript/AJAX):

    • HTML: Provides the basic structure of the calculator, including buttons for digits and operations.
    • CSS: Styles the calculator to make it look better.
    • JavaScript/AJAX:
      • appendToDisplay(value): Appends the clicked button's value to the display.
      • clearDisplay(): Clears the display.
      • calculate(): Sends the expression to calculate.php via AJAX, receives the result, and displays it.
  2. Backend (PHP):

    • calculate.php:
      • Receives the expression from the client.
      • Sanitizes the expression to prevent security issues.
      • Uses eval() to compute the result of the expression.
      • Returns the result to the frontend.

This setup provides a functional basic calculator with a clean interface and responsive behavior using AJAX to handle calculations.

Connecting Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

Source Code

Top comments (3)

Collapse
 
ravavyr profile image
Ravavyr

This is a nice tutorial, but you're writing PHP and JS like it's 2010.

A few important items that should be changed for 2024.

  • don't use onclick, but rather addEventListener to add a click event to all the buttons in one go instead of typing a function name for each one. Replacing appendToDisplay with:
    js
    document.querySelectorAll(".calculator .buttons button").forEach(function(btn){
    btn.addEventListener("click", function(){
    document.getElementById('display').value += value;
    });
    });

  • don't use xhr for your requests, but rather fetch which is simpler to use and is what modern JS uses

  • you're using "eval" in php, that is disabled on a lot of hosting servers because it's a security vulnerability, especially because you're processing "user input" via GET

  • You should also be using POST to send the data instead of GET , GET is far easier to abuse with a bot attack than POST is especially if you set some sort of authentication on the endpoint.

Lastly...this is a PHP tutorial so fine, you had to do it in PHP, but anyone creating a calculator today would just be writing all of it in JS, this way the server load is completely reduced since each keystroke doesn't have to make a fetch request to your server and would just run in the users browser client-side.

I'm not writing this out to be a pain, but hopefully to help anyone who reads this, write better, more modern and cleaner code. Your tutorial is not bad, just needs some modernizing and securing.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.