封裝 $_GET、$_POST、$_REQUEST、$_COOKIE、$_FILES,提供:
htmlspecialchars)false 表示不存在)<?php
class Request {
private $get, $post, $request, $cookie, $files;
private static $instance;
private function __construct() {
$this->get = self::format($_GET);
$this->post = self::format($_POST);
$this->request = array_merge($this->get, $this->post);
$this->cookie = self::format($_COOKIE);
$this->files = self::format($_FILES);
}
public static function getInstance() {
if (!(self::$instance instanceof self)) {
self::$instance = new self();
}
return self::$instance;
}
// 取得整數
public function getInt($source, $key) {
$data = $this->{$source};
return isset($data[$key]) ? intval($data[$key]) : false;
}
public function get_int($key) { return $this->getInt('get', $key); }
public function post_int($key) { return $this->getInt('post', $key); }
public function request_int($key) { return $this->getInt('request', $key); }
public function cookie_int($key) { return $this->getInt('cookie', $key); }
// 取得字串 (可選過濾)
public function getString($source, $key, $filter = true) {
$data = $this->{$source};
if (!isset($data[$key])) return false;
return $filter ? $this->filter($data[$key]) : $data[$key];
}
public function get_str($key, $filter = true) { return $this->getString('get', $key, $filter); }
public function post_str($key, $filter = true) { return $this->getString('post', $key, $filter); }
public function request_str($key, $filter = true) { return $this->getString('request', $key, $filter); }
public function cookie_str($key, $filter = true) { return $this->getString('cookie', $key, $filter); }
// 檔案上傳資訊 (陣列)
public function file($key) { return $this->files[$key] ?? null; }
private static function format($data) {
$result = [];
if (!is_array($data)) return $result;
foreach ($data as $k => $v) {
$result[$k] = is_array($v) ? $v : trim($v);
}
return $result;
}
private function filter($data) {
if (is_array($data)) {
return array_map(function($v) { return htmlspecialchars($v, ENT_QUOTES); }, $data);
}
return htmlspecialchars($data, ENT_QUOTES);
}
}
// 使用範例
$req = Request::getInstance();
$id = $req->get_int('id');
$name = $req->post_str('username');
$file = $req->file('avatar');
| 亮點 | 不足/改進 |
|---|---|
| 集中處理輸入,減少重複 trim/filter | 單例模式難以單元測試,建議依賴注入 |
| 型別安全 (int/string) | 缺少浮點數、布林、陣列、日期等型別支援 |
| 檔案上傳資訊完整保留 | 無 CSRF Token 驗證、無輸入驗證規則引擎 |
| 程式碼簡潔易懂 | PHP 7+ 建議加入型別宣告、嚴格模式 |
nyholm/psr7-server、laminas/laminas-httphandlerrunner。$request->input()、Symfony Request::createFromGlobals()、Yii Yii::$app->request。respect/validation、vlucas/valitron、illuminate/validation。