method="get" → 使用 $_GET 取得資料method="post" → 使用 $_POST 取得資料兩者差異請參考「HTML Form GET 與 POST 差異」。
<form action="post.php" method="post">
Name: <input type="text" name="username" />
<input type="submit" value="ok" />
</form>
<?php echo $_POST["username"]; ?>
// 輸入 Jacky → 輸出:You are Jacky.
關鍵:$_POST["username"] 中的 username 對應 <input name="username">。
<form action="radiopost.php" method="post">
<input type="radio" name="fruit" value="Apple">Apple<br />
<input type="radio" name="fruit" value="Orange">Orange<br />
<input type="radio" name="fruit" value="Mango">Mango<br />
<input type="submit" value="ok">
</form>
<?php echo $_POST["fruit"]; ?>
// 選擇 Orange → 輸出:Orange
同名 name="fruit" 的單選按鈕同一時間只能選一個,$_POST["fruit"] 取得被選項目的 value。
[])<form action="checkboxpost.php" method="post">
<input type="checkbox" name="fruit[]" value="Apple">Apple<br />
<input type="checkbox" name="fruit[]" value="Orange">Orange<br />
<input type="checkbox" name="fruit[]" value="Mango">Mango<br />
<input type="submit" value="ok">
</form>
<?php
echo count($_POST["fruit"]), "<br />";
foreach ($_POST["fruit"] as $value) {
echo $value, "<br />";
}
?>
勾選 Orange、Mango → 輸出:
2
Orange
Mango
| 表單類型 | name 寫法 | $_POST 回傳型態 | 取值方式 |
|---|---|---|---|
| 文字框 | name="username" | 字串 | $_POST["username"] |
| 單選鈕 | name="fruit" (同名) | 字串 | $_POST["fruit"] |
| 複選框 | name="fruit[]" (加中括號) | 陣列 | foreach ($_POST["fruit"] as $v) |
htmlspecialchars() 防 XSSisset($_POST['key']) 避免 Undefined index 警告