表單提交後,PHP 自動將 name 屬性值轉為同名變量 (註冊全局變量已棄用/移除),現代寫法統一使用超全局數組:
$_POST['name']、$_GET['name']、$_REQUEST['name']$_FILES['field']<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>問卷調查</title></head><body>
<?php
function showForm(): void {
global $PHP_SELF; // 老代碼習慣,現代用 $_SERVER['PHP_SELF']
?>
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
姓名: <input type="text" name="name" required><br>
最愛起司:
<input type="radio" name="cheese" value="brie" required> 法國布里
<input type="radio" name="cheese" value="cheddar"> 英國切達
<input type="radio" name="cheese" value="mozzarella"> 義大利水牛芝士<br>
喜歡吃起司的時段 (多選):
<input type="checkbox" name="times[]" value="m"> 早晨
<input type="checkbox" name="times[]" value="n"> 中午
<input type="checkbox" name="times[]" value="d"> 晚餐
<input type="checkbox" name="times[]" value="l"> 宵夜<br>
<input type="hidden" name="stage" value="process">
<button type="submit">提交</button>
</form>
<?php
}
function processForm(): void {
$name = trim($_POST['name'] ?? '');
$cheese = $_POST['cheese'] ?? '';
$times = $_POST['times'] ?? []; // 自動為數組
$timesStr = implode(', ', $times);
echo "<h2>感謝 $name 參與調查!</h2>";
echo "最愛起司: $cheese<br>";
echo "時段: $timesStr<br>";
echo '<a href="?stage=form">重新填寫</a>';
}
// 路由
$stage = $_GET['stage'] ?? ($_POST['stage'] ?? 'form');
if ($stage === 'process') processForm();
else showForm();
?>
</body></html>
name="times[] 方括號讓 PHP 自動構建數組 $_POST['times']。stage 區分顯示表單/處理結果。htmlspecialchars(),SQL 用預處理,CSRF 令牌保護表單。enctype="multipart/form-data",$_FILES['file']['tmp_name']、['name']、['size']、['error'],用 move_uploaded_file() 移動。