| 變數 | 來源 | 適用場景 | 安全性 | 優先順序 |
|---|---|---|---|---|
$_GET | URL 查詢字串 ?key=val | 查詢、分頁、搜尋、可分享連結 | 低(明文、記錄在日誌) | 最低 |
$_POST | HTTP Body (form-data) | 表單送出、狀態變更、敏感資料 | 中(不在 URL、但可被攔截) | 中 |
$_REQUEST | $_GET + $_POST + $_COOKIE | 快速原型、不確定來源 | 低(合併來源、順序依設定) | 最高 (預設 GPC) |
; php.ini 設定
request_order = "GP" ; $_REQUEST = $_GET + $_POST (後者覆蓋前者)
; 或
request_order = "GPC" ; 包含 Cookie (不推薦,安全風險)
預設 `GPC` 導致 Cookie 可覆蓋 GET/POST 參數,極度危險。
<?php
// ❌ 不推薦:來源模糊,安全風險
$id = $_REQUEST['id'] ?? 0;
// ✅ 推薦:明確來源,語意清晰
$id = $_GET['id'] ?? 0; // 查詢、分頁
$userId = $_POST['user_id'] ?? 0; // 表單提交、刪除操作
$token = $_COOKIE['token'] ?? ''; // 明確從 Cookie 取得
?>
<?php
/**
* 統一輸入取得函數
*/
function input(string $key, $default = null, string $source = 'auto') {
$source = strtolower($source);
$value = null;
switch ($source) {
case 'get': $value = $_GET[$key] ?? $default; break;
case 'post': $value = $_POST[$key] ?? $default; break;
case 'cookie': $value = $_COOKIE[$key] ?? $default; break;
case 'auto':
default:
// 建議順序:POST > GET > COOKIE (對應 request_order=GP)
$value = $_POST[$key] ?? $_GET[$key] ?? $_COOKIE[$key] ?? $default;
}
// 類型轉換與清理
if (is_string($value)) {
$value = trim($value);
}
return $value;
}
// 使用範例
$page = input('page', 1, 'get'); // 分頁參數
$username = input('username', '', 'post'); // 登入表單
$csrf = input('_token', '', 'post'); // CSRF Token
$lang = input('lang', 'zh-TW', 'cookie'); // 偏好設定
?>
<?php
// 簡易 Request 類別
class Request {
private array $get;
private array $post;
private array $cookie;
private array $files;
private array $server;
public static function capture(): self {
$req = new self();
$req->get = $_GET;
$req->post = $_POST;
$req->cookie = $_COOKIE;
$req->files = $_FILES;
$req->server = $_SERVER;
return $req;
}
public function get(string $key, $default = null) { return $this->get[$key] ?? $default; }
public function post(string $key, $default = null) { return $this->post[$key] ?? $default; }
public function cookie(string $key, $default = null) { return $this->cookie[$key] ?? $default; }
public function file(string $key) { return $this->files[$key] ?? null; }
public function header(string $name) {
$key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
return $this->server[$key] ?? null;
}
public function ip(): string {
return $this->server['REMOTE_ADDR'] ?? 'unknown';
}
public function method(): string {
return $this->server['REQUEST_METHOD'] ?? 'GET';
}
public function all(): array {
return array_merge($this->get, $this->post);
}
}
// 使用
$request = Request::capture();
$page = $request->get('page', 1);
$email = $request->post('email');
?>
$_GET/$_POST/$_COOKIE)htmlspecialchars()、json_encode()$_REQUESTextract($_REQUEST) 或 import_request_variables()