簡易計算器是 PHP 表單處理、條件分支、狀態管理的經典入門專案。本文提供完整單檔案實現,涵蓋 HTML 表單、後端運算、結果顯示與 Session 保持。
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
// 處理表單提交
$result = null;
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$num1 = isset($_POST['num1']) ? (float)$_POST['num1'] : null;
$num2 = isset($_POST['num2']) ? (float)$_POST['num2'] : null;
$oper = $_POST['oper'] ?? '';
if ($num1 === null || $num2 === null) {
$error = '請輸入有效數字';
} elseif (!in_array($oper, ['+', '-', '*', '/'])) {
$error = '無效運算符';
} else {
switch ($oper) {
case '+': $result = $num1 + $num2; break;
case '-': $result = $num1 - $num2; break;
case '*': $result = $num1 * $num2; break;
case '/':
if ($num2 == 0) {
$error = '除數不能為零';
} else {
$result = $num1 / $num2;
}
break;
}
}
// 保存結果到 Session (可選)
if ($result !== null) {
$_SESSION['last_result'] = $result;
$_SESSION['last_expr'] = "$num1 $oper $num2 = $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; }
label { display: inline-block; width: 80px; }
input, select { padding: 0.5rem; }
.result { padding: 1rem; background: #f0f0f0; margin-top: 1rem; }
.error { color: red; }
.history { font-size: 0.9em; color: #666; margin-top: 1rem; }
</style>
</head>
<body>
<h1>簡易計算器</h1>
<form method="POST">
<div class="form-group">
<label>第一個數</label>
<input type="number" step="any" name="num1" required value="<?= htmlspecialchars($_POST['num1'] ?? '') ?>">
</div>
<div class="form-group">
<label>運算符號</label>
<select name="oper">
<option value="+" <?= ($_POST['oper'] ?? '') === '+' ? 'selected' : '' ?>>+</option>
<option value="-" <?= ($_POST['oper'] ?? '') === '-' ? 'selected' : '' ?>>-</option>
<option value="*" <?= ($_POST['oper'] ?? '') === '*' ? 'selected' : '' ?>>×</option>
<option value="/" <?= ($_POST['oper'] ?? '') === '/' ? 'selected' : '' ?>>÷</option>
</select>
</div>
<div class="form-group">
<label>第二個數</label>
<input type="number" step="any" name="num2" required value="<?= htmlspecialchars($_POST['num2'] ?? '') ?>">
</div>
<button type="submit">計算結果</button>
</form>
<?php if ($error): ?>
<div class="error"><?= $error ?></div>
<?php elseif ($result !== null): ?>
<div class="result">
<strong>結果:</strong> <?= $result ?>
</div>
<?php endif; ?>
<?php if (isset($_SESSION['last_expr'])): ?>
<div class="history">上次計算:<?= $_SESSION['last_expr'] ?></div>
<?php endif; ?>
</body></html>
| 概念 | 代碼體現 | 說明 |
|---|---|---|
| 表單提交 | $_SERVER['REQUEST_METHOD'] === 'POST' | 區分 GET 顯示與 POST 提交 |
| 輸入驗證 | (float)$_POST['num1'] + 空值檢查 | 類型轉換與業務驗證分離 |
| Switch 分支 | switch($oper) | 離散值多路分支最佳選擇 |
| 除零保護 | if ($num2 == 0) | 業務邊界條件必須顯式處理 |
| XSS 防護 | htmlspecialchars() 輸出轉義 | 所有動態輸出必須轉義 |
| 狀態保持 | $_SESSION['last_result'] | 跨請求共享資料 |
| 表單回填 | value="= $_POST['num1'] ?? '' ?>" | 提升用戶體驗 |
$_SESSION['history'][] = $expr,顯示最近 10 筆%、**、sqrt、powfetch() 發送 JSON,返回 {result: 100}calculate($a, $op, $b) 純函數,PHPUnit 測試error_log() 記錄異常輸入與系統錯誤隨著功能增長,建議採用 MVC 分層:
Calculator 類封裝運算邏輯calculator.phtml這個簡單專案蘊含了 Web 開發的核心要素:輸入→處理→輸出、狀態管理、安全防護、用戶體驗,是新手邁向實戰的最佳練習。