<!-- hello.html -->
<form action="hello.php" method="get">
姓名:<input name="name" type="text" />
<input type="submit" />
</form>
<?php
// hello.php
header('Content-Type: text/html; charset=utf-8');
$name = $_GET['name'] ?? '';
echo $name ? "Hello {$name}" : 'Please input name';
?>
特點:參數顯示在 URL、長度受限(~2KB)、可收藏/分享、適合冪等查詢操作。
<!-- add.html -->
<form action="add.php" method="post">
<input name="num1" type="number" /> +
<input name="num2" type="number" />
<input type="submit" value="相加" />
</form>
<?php // add.php $n1 = $_POST['num1'] ?? ''; $n2 = $_POST['num2'] ?? ''; echo ($n1 !== '' && $n2 !== '') ? ($n1 + $n2) : 'Please input num'; ?>
特點:數據在請求體、無長度限制、不曝露於 URL、適合狀態變更操作(增刪改)。
| 維度 | GET | POST |
|---|---|---|
| 數據位置 | URL Query String | Request Body |
| 長度限制 | ~2KB (瀏覽器/服務器) | 無 (受 post_max_size) |
| 可見性 | 地址欄可見 | 不可見 |
| 緩存/收藏 | 可緩存、可收藏 | 不可緩存 |
| 語義 | 安全、冪等(查詢) | 非冪等(狀態變更) |
| 編碼 | application/x-www-form-urlencoded | 支援 multipart/form-data (上傳) |
csrf_token,Session 驗證。action="" 或省略 action 皆提交至當前頁面 URL,符合 HTML5 標準。