HTML 中同名 Checkbox 需使用 name="field[] 陣列語法,PHP 才能接收多個值。本文詳解前後端配合要點與進階處理技巧。
<form method="post" action="process.php">
<label><input type="checkbox" name="interests[]" value="php"> PHP</label>
<label><input type="checkbox" name="interests[]" value="js"> JavaScript</label>
<label><input type="checkbox" name="interests[]" value="python"> Python</label>
<label><input type="checkbox" name="interests[]" value="go"> Go</label>
<label><input type="checkbox" name="interests[]" value="rust"> Rust</label>
<button type="submit">提交</button>
</form>
關鍵點:
name="interests[] 方括號告訴 PHP 這是陣列$_POST['interests'] 為數組<?php
// 安全獲取,防止未勾選導致 Undefined array key
$interests = $_POST['interests'] ?? [];
// 類型檢查與清洗
if (!is_array($interests)) {
$interests = []; // 防止惡意提交字符串
}
// 過濾非法值(白名單機制)
$allowed = ['php', 'js', 'python', 'go', 'rust'];
$interests = array_intersect($interests, $allowed);
// 結果處理
if ($interests) {
echo "用戶選擇:" . implode(', ', $interests);
// 存入資料庫可用 json_encode 或 implode
$storageValue = json_encode($interests); // 推薦 JSON 格式
} else {
echo "未選擇任何項目";
}
?>
<!-- HTML -->
<input type="checkbox" name="skills[php]" value="1"> PHP
<input type="checkbox" name="skills[js]" value="1"> JavaScript
<?php
// PHP 接收到 $_POST['skills'] = ['php' => '1', 'js' => '1']
$skills = array_keys($_POST['skills'] ?? []); // 獲取 ['php', 'js']
?>
<!-- HTML -->
<input type="checkbox" name="user[1][roles][]" value="admin">
<input type="checkbox" name="user[1][roles][]" value="editor">
<input type="checkbox" name="user[2][roles][]" value="viewer">
<?php
// $_POST['user'] = [
// 1 => ['roles' => ['admin', 'editor']],
// 2 => ['roles' => ['viewer']]
// ]
foreach ($_POST['user'] as $uid => $data) {
$roles = $data['roles'] ?? [];
// 處理每個用戶的角色...
}
?>
<?php
$selected = $_POST['interests'] ?? [];
$allOptions = ['php', 'js', 'python', 'go', 'rust'];
?>
<form method="post">
<?php foreach ($allOptions as $opt): ?>
<label>
<input type="checkbox" name="interests[]" value="<?= htmlspecialchars($opt) ?>"
<?= in_array($opt, $selected) ? 'checked' : '' ?>>
<?= htmlspecialchars($opt) ?>
</label>
<?php endforeach; ?>
<button type="submit">更新</button>
</form>
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
name="interest" | 覆蓋前值,只獲取最後一個 | name="interest[]" |
直接 implode($_POST['interests']) | 未勾選時報錯/警告 | implode(',', $_POST['interests'] ?? []) |
| 未驗證直接入庫 | XSS、注入風險 | 白名單過濾 + 預處理語句 |
未檢查 is_array() | 惡意提交字符串導致錯誤 | 強制轉換 (array) 或 ?? [] |
<?php
// Laravel Request
$interests = $request->input('interests', []); // 自動處理數組、默認值
$interests = $request->array('interests'); // 強制轉數組
// ThinkPHP Request
$interests = Request::param('interests/a'); // /a 強制轉數組
$interests = Request::post('interests/a', []); // 同理
?>