系統說明 PHP 接收表單資料的三大超全域變數:$_POST、$_GET、$_REQUEST,並提供從基礎到進階的完整表單處理範例,包含驗證、郵件發送。
| 變數 | 來源 | 特性 |
|---|---|---|
$_GET | URL 參數 | 可見、長度受限、可書籤分享 |
$_POST | HTTP Body | 不可見、無長度限制、適合敏感/大量資料 |
$_REQUEST | GET+POST+COOKIE | 合併來源,順序受 variables_order 影響,不建議常用 |
<?php
if (!empty($_POST['guess'])) {
echo 'last guess: ' . htmlspecialchars($_POST['guess']);
}
?>
<form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<p>Type your guess: <input type="text" name="guess"></p>
</form>
<?php
$self = $_SERVER['PHP_SELF'];
$username = $_POST['username'] ?? '';
$useraddr = $_POST['useraddr'] ?? '';
$comments = $_POST['comments'] ?? '';
$sent = $_POST['sent'] ?? '';
$form = '<form action="' . $self . '" method="post">'
. 'Name: <input type="text" name="username" size="30" value="' . htmlspecialchars($username) . '"><br>'
. 'Email: <input type="text" name="useraddr" size="30" value="' . htmlspecialchars($useraddr) . '"><br>'
. 'Comments: <textarea name="comments">' . htmlspecialchars($comments) . '</textarea><br>'
. '<input type="submit" name="sent" value="Send Form">'
. '</form>';
if ($sent) {
$valid = true; $errmsg = '';
if (!$username) { $errmsg .= 'Enter your name...<br>'; $valid = false; }
if (!$useraddr) { $errmsg .= 'Enter your email...<br>'; $valid = false; }
if (!$comments) { $errmsg .= 'Enter your comments...<br>'; $valid = false; }
$useraddr = trim($useraddr);
// 簡易 Email 格式驗證
if (!preg_match('/^[-!#$%&\'*+\/0-9=?A-Z^_`{|}~]+@([-0-9A-Z]+\.)+[0-9A-Z]{2,4}$/i', $useraddr)) {
$errmsg .= 'Email format incorrect!<br>'; $valid = false;
}
if (!$valid) {
echo $errmsg . $form;
} else {
$to = 'php@example.com';
$subject = 'Feedback from ' . $username;
$headers = 'From: ' . $useraddr . '\r\n'
. 'Content-Type: text/html; charset=iso-8859-1\r\n';
if (mail($to, $subject, $comments, $headers)) {
echo "Your comments have been sent - thanks $username";
}
}
} else {
echo $form;
}
?>
htmlspecialchars() 防 XSS。$_FILES)。