應用場景
- 分頁導航需保留原查詢參數
- 表單驗證失敗回顯,需保持用戶輸入
- 多步驟精靈流程,跨步驟傳遞隱藏參數
- URL 重寫時動態增減參數
通用函數 getplus() 完整實作
<?php
/**
* 保留/修改/新增 GET/POST 參數,生成新查詢字串
* @param string $x 參數名
* @param string $value 參數值
* @param string $plus 'close'=覆蓋模式, 其他=新增模式
* @param string $method 'all'|'get'|'post' 資料來源
* @return string 完整查詢字串(含前導 ? 或 &)
*/
function getplus($x = '', $value = '', $plus = 'close', $method = 'all') {
global $_GET, $_POST;
$sources = array();
if ($method === 'all') { $sources[] = $_GET; $sources[] = $_POST; }
elseif ($method === 'get') { $sources[] = $_GET; }
elseif ($method === 'post') { $sources[] = $_POST; }
$temp = '';
$i = 1;
$found = false;
foreach ($sources as $source) {
foreach ($source as $k => $v) {
if ($k === $x) { $v = $value; $found = true; }
$sep = ($i === 1) ? '?' : '&';
$temp .= "{$sep}{$k}=" . urlencode($v);
$i++;
}
}
if (!$found) {
$sep = (strpos($temp, '?') !== false || strpos($temp, '=') !== false) ? '&' : '?';
$temp .= "{$sep}{$x}=" . urlencode($value);
} elseif ($plus !== 'close') {
$sep = (strpos($temp, '?') !== false || strpos($temp, '=') !== false) ? '&' : '?';
$temp .= "{$sep}{$x}=" . urlencode($value);
}
return $temp;
}
?>
使用範例
<?php
// 原 URL: ?page=2&sort=desc&keyword=test
// 1. 修改 page 為 3,保留其他
echo getplus('page', 3);
// 輸出: ?page=3&sort=desc&keyword=test
// 2. 新增 category=php(不覆蓋模式)
echo getplus('category', 'php', 'add');
// 輸出: ?page=2&sort=desc&keyword=test&category=php
// 3. 僅處理 GET 參數
echo getplus('page', 1, 'close', 'get');
?>
進階建議
- 生產環境建議使用
http_build_query() 配合陣列操作,更標準、安全
- 參數值務必經
urlencode() 編碼,防止 XSS 與 URL 解析錯誤
- 避免直接操作
$_GET/$_POST 超全域變數,封裝為請求物件更利測試