首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 簡易計算器實現:表單處理、Session 保持與運算邏輯封裝

     編輯:PHP 相關知識

通過一個完整的四則運算計算器示例,演示 PHP 表單自提交、Session 狀態保持、運算邏輯封裝與 XSS 防護的基礎實踐。

單文件完整實現

<?php
session_start();

// 運算邏輯封裝
function calculate(float $a, float $b, string $op): float|string {
    return match ($op) {
        '+' => $a + $b,
        '-' => $a - $b,
        '*' => $a * $b,
        '/' => $b != 0 ? $a / $b : '除數不能為零',
        default => '非法運算符'
    };
}

// 處理提交
$result = null;
$num1 = $num2 = '';
$operator = '+';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $num1 = $_POST['num1'] ?? '';
    $num2 = $_POST['num2'] ?? '';
    $operator = $_POST['oper'] ?? '+';

    // 輸入驗證與過濾
    $num1 = filter_var($num1, FILTER_VALIDATE_FLOAT);
    $num2 = filter_var($num2, FILTER_VALIDATE_FLOAT);

    if ($num1 !== false && $num2 !== false) {
        $result = calculate($num1, $num2, $operator);
        // 存入 Session 供刷新後顯示
        $_SESSION['last_calc'] = [
            'num1' => $num1,
            'num2' => $num2,
            'oper' => $operator,
            'result' => $result,
            'time' => date('Y-m-d H:i:s')
        ];
    } else {
        $result = '請輸入有效數字';
    }
} elseif (isset($_SESSION['last_calc'])) {
    // 頁面刷新恢復上次結果
    $last = $_SESSION['last_calc'];
    $num1 = $last['num1'];
    $num2 = $last['num2'];
    $operator = $last['oper'];
    $result = $last['result'];
}
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>PHP 簡易計算器</title>
    <style>
        body {font-family: sans-serif; max-width: 400px; margin: 2rem auto;}
        .form-group {margin-bottom: 1rem; display: flex; gap: 0.5rem; align-items: center;}
        label {min-width: 80px;}
        input, select {padding: 0.5rem; flex: 1;}
        button {padding: 0.5rem 1.5rem; background: #007bff; color: white; border: none; cursor: pointer;}
        .result {margin-top: 1.5rem; padding: 1rem; background: #f8f9fa; border-radius: 4px;}
        .error {color: #dc3545;}
    </style>
</head>
<body>
    <h1>簡易計算器</h1>
    <form method="post" action="">
        <div class="form-group">
            <label>第一個數</label>
            <input type="text" name="num1" value="<?= htmlspecialchars($num1) ?>" required>
        </div>
        <div class="form-group">
            <label>運算符號</label>
            <select name="oper">
                <option value="+" <?= $operator==='+'?'selected':'' ?>>+</option>
                <option value="-" <?= $operator==='-'?'selected':'' ?>>-</option>
                <option value="*" <?= $operator==='*'?'selected':'' ?>>×</option>
                <option value="/" <?= $operator==='/'?'selected':'' ?>>÷</option>
            </select>
        </div>
        <div class="form-group">
            <label>第二個數</label>
            <input type="text" name="num2" value="<?= htmlspecialchars($num2) ?>" required>
        </div>
        <button type="submit">計算結果</button>
    </form>

    <?php if ($result !== null): ?>
    <div class="result <?= is_string($result) && str_starts_with($result, '非法') ? 'error' : '' ?>">
        <strong>計算結果:</strong>
        <?= is_float($result) ? number_format($result, 10, '.', '') : htmlspecialchars($result) ?>
        <br><small>表達式:<?= htmlspecialchars($num1) ?> <?= htmlspecialchars($operator) ?> <?= htmlspecialchars($num2) ?> = <?= is_float($result) ? number_format($result, 10, '.', '') : htmlspecialchars($result) ?></small>
    </div>
    <?php endif; ?>
</body>
</html>

關鍵知識點解析

  1. 表單自提交:action="" 郵寄到當前 URL,同一檔案處理顯示與邏輯;
  2. 輸入過濾:filter_var($val, FILTER_VALIDATE_FLOAT) 同時驗證並轉型,拒絕非數字;
  3. XSS 防護:輸出變量統一用 htmlspecialchars();
  4. Session 保持:計算結果寫入 $_SESSION,頁面刷新不丟失;
  5. 除零保護:match 表達式中顯式判斷 $b != 0;
  6. 浮點數顯示:number_format($result, 10, '.', '') 避免科學計數法,保留精度。

進階擴展方向

  • 支援鍵盤輸入表達式(如 eval() 配合白名單正則,極度謹慎);
  • 引入 mattleffler/calculator 庫支援括號、函數、變量;
  • API 模式:返回 JSON,前端 Vue/React 渲染,實現無刷新計算;
  • 歷史記錄:Session 存儲陣列,顯示最近 10 次計算。

這個簡單示例涵蓋了 PHP Web 開發的核心流程:請求處理 → 數據驗證 → 業務邏輯 → 狀態管理 → 安全輸出。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved