首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 表單處理入門:$_POST、$_GET、$_REQUEST 自動全域變數詳解

     編輯:PHP 綜合知識

核心概念

PHP 自動將表單提交資料轉為超全域陣列,無需手動解析:

  • $_POST:method="POST" 表單資料
  • $_GET:method="GET" 或 URL 參數
  • $_REQUEST:合併 $_GET、$_POST、$_COOKIE、$_FILES

最小範例:HTML 表單 + PHP 處理

<!-- form.html -->
<form action="action.php" method="POST">
  Your name: <input type="text" name="name" />
  Your age: <input type="text" name="age" />
  <input type="submit" />
</form>
<!-- action.php -->
Hi <?php echo htmlspecialchars($_POST["name"]); ?>.
You are <?php echo (int)$_POST["age"]; ?> years old.

輸出範例

Hi Joe.
You are 22 years old.

安全關鍵點

  1. 永不信任輸入: 輸出到 HTML 必經 htmlspecialchars()
  2. 型別轉換: 數值欄位用 (int)、(float) 強制轉型
  3. 來源明確: 明確使用 $_POST 或 $_GET,避免 $_REQUEST 混淆來源
  4. CSRF 防護: 重要操作加入 Token 驗證

進階:檔案上傳處理

<form action="upload.php" method="POST" enctype="multipart/form-data">
  <input type="file" name="avatar" />
  <input type="submit" />
</form>

// upload.php
$file = $_FILES['avatar'];
if ($file['error'] === UPLOAD_ERR_OK) {
    move_uploaded_file($file['tmp_name'], "/uploads/{$file['name']}");
}

配置影響

  • post_max_size:POST 總資料大小限制(預設 8M)
  • upload_max_filesize:單檔上傳限制(預設 2M)
  • max_input_vars:最大輸入變數數量(預設 1000,防陣列攻擊)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved