完整單文件實現(jisuan.php)
<?php
header("Content-Type: text/html; charset=utf-8");
session_start();
$rs = null;
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$num1 = $_POST['num1'] ?? '';
$num2 = $_POST['num2'] ?? '';
$oper = $_POST['oper'] ?? '';
// 輸入驗證
if (!is_numeric($num1) || !is_numeric($num2)) {
$error = "請輸入有效數字";
} else {
switch ($oper) {
case '+': $rs = $num1 + $num2; break;
case '-': $rs = $num1 - $num2; break;
case '*': $rs = $num1 * $num2; break;
case '/':
if ($num2 == 0) {
$error = "除數不能為零";
} else {
$rs = $num1 / $num2;
}
break;
default: $error = "無效運算符";
}
}
if ($rs !== null) $_SESSION['rs'] = $rs;
}
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>簡單計算機</title>
<style>
body{font-family:sans-serif;max-width:400px;margin:2rem auto;padding:1rem;}
label{display:block;margin:0.5rem 0;}
input,select{padding:0.5rem;width:100%;box-sizing:border-box;}
button{padding:0.7rem 1.5rem;background:#007bff;color:#fff;border:none;border-radius:4px;cursor:pointer;}
.error{color:red;margin:0.5rem 0;}
.result{font-size:1.2rem;font-weight:bold;margin:1rem 0;color:#28a745;}
</style></head><body>
<h2>PHP 簡易計算機</h2>
<form method="post">
<label>第一個數:<input type="text" name="num1" value="<?= htmlspecialchars($_POST['num1'] ?? '') ?>" required></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>
</label>
<label>第二個數:<input type="text" name="num2" value="<?= htmlspecialchars($_POST['num2'] ?? '') ?>" required></label>
<button type="submit">計算</button>
</form>
<?php if ($error): ?><div class="error"><?= $error ?></div><?php endif; ?>
<?php if ($rs !== null): ?><div class="result">計算結果:<?= $rs ?></div><?php endif; ?>
<?php if (isset($_SESSION['rs'])): ?><p>上次結果(Session):<?= $_SESSION['rs'] ?></p><?php endif; ?>
</body></html>
關鍵點解析
- 同文件處理表單:`action=""` 或省略,`$_SERVER['REQUEST_METHOD']` 區分 GET/POST。
- 輸入驗證:`is_numeric()` 防止非數字導致錯誤/注入。
- 除零保護:除法前檢查 `$num2 == 0`。
- XSS 防護:輸出用戶輸入時用 `htmlspecialchars()`。
- Session 保持:計算結果存入 `$_SESSION['rs']`,刷新頁面仍可見上次結果。
- 保持表單值:提交後將值回填 `value` 屬性,提升體驗。
進階擴展方向
- AJAX 無刷新計算:前端 JS 發送 fetch/axios,後端返回 JSON。
- 科學計算器**:支持括號、函數(sin、log、pow)、運算符優先級(用 Shunting-yard 算法或 `eval` 但極度危險)。
- 歷史記錄**:Session 存儲陣列,顯示最近 10 條計算記錄。
- 單位換算/匯率轉換**:擴展為實用工具頁。