萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取表單資料完整教學($_POST, $_GET, $_REQUEST)

系統說明 PHP 接收表單資料的三大超全域變數:$_POST、$_GET、$_REQUEST,並提供從基礎到進階的完整表單處理範例,包含驗證、郵件發送。

超全域變數比較

變數來源特性
$_GETURL 參數可見、長度受限、可書籤分享
$_POSTHTTP Body不可見、無長度限制、適合敏感/大量資料
$_REQUESTGET+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。
  • 資料庫寫入前使用 Prepared Statement(PDO/MySQLi)。
  • CSRF 保護:表單加入一次性 Token。
  • 檔案上傳另行處理(見 $_FILES)。
copyright © 萬盛學電腦網 all rights reserved