通過一個完整的四則運算計算器示例,演示 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>
action="" 郵寄到當前 URL,同一檔案處理顯示與邏輯;filter_var($val, FILTER_VALIDATE_FLOAT) 同時驗證並轉型,拒絕非數字;htmlspecialchars();$_SESSION,頁面刷新不丟失;match 表達式中顯式判斷 $b != 0;number_format($result, 10, '.', '') 避免科學計數法,保留精度。eval() 配合白名單正則,極度謹慎);這個簡單示例涵蓋了 PHP Web 開發的核心流程:請求處理 → 數據驗證 → 業務邏輯 → 狀態管理 → 安全輸出。