| Smarty 變數 | 對應 \$_SERVER | 輸出範例 | 說明 |
|---|---|---|---|
{$smarty.server.SERVER_NAME} | `$_SERVER['SERVER_NAME']` | `www.example.com` | 伺服器主機名(受 `UseCanonicalName` 影響) |
{$smarty.server.HTTP_HOST} | `$_SERVER['HTTP_HOST']` | `www.example.com:8080` | 客戶端 Host 標頭,**含埠號**,反向代理下更可靠 |
{$smarty.server.REQUEST_URI} | `$_SERVER['REQUEST_URI']` | `/path/to/page?query=1` | 請求路徑+查詢字串,**不含域名** |
{$smarty.server.HTTPS} | `$_SERVER['HTTPS']` | `on` / 空 | 判斷是否 HTTPS |
{$smarty.server.SERVER_PORT} | `$_SERVER['SERVER_PORT']` | `80` / `443` / `8080` | 伺服器埠號 |
{* https://{$smarty.server.SERVER_NAME}{$smarty.server.REQUEST_URI} *}
{* 輸出:https://www.example.com/path?query=1 *}
{* 判斷協議 *}
{assign var="protocol" value="http"}
{if $smarty.server.HTTPS == 'on' || $smarty.server.SERVER_PORT == 443}
{assign var="protocol" value="https"}
{/if}
{* 判斷是否需顯示埠號 *}
{assign var="host" value=$smarty.server.HTTP_HOST}
{if ($protocol == 'http' && $smarty.server.SERVER_PORT != 80) ||
($protocol == 'https' && $smarty.server.SERVER_PORT != 443)}
{* HTTP_HOST 已含埠號,直接用 *}
{else}
{* 標準埠號,移除 HTTP_HOST 中的埠號 *}
{assign var="host" value=$smarty.server.SERVER_NAME}
{/if}
{* 最終 URL *}
{$protocol}://{$host}{$smarty.server.REQUEST_URI}
<?php
// PHP 端
function currentFullUrl(): string {
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'];
$uri = $_SERVER['REQUEST_URI'] ?? '/';
// 標準埠不顯示
if (($scheme === 'http' && $_SERVER['SERVER_PORT'] == 80) ||
($scheme === 'https' && $_SERVER['SERVER_PORT'] == 443)) {
$host = $_SERVER['SERVER_NAME'];
}
return "{$scheme}://{$host}{$uri}";
}
$smarty->assign('current_url', currentFullUrl());
$smarty->assign('current_path', $_SERVER['REQUEST_URI'] ?? '/');
$smarty->assign('current_host', $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME']);
// 模板中直接使用
當前頁完整 URL
當前頁路徑
域名:{$current_host}
{* 當前路徑以 /products 開頭 *}
{if $current_path|strpos:'/products' === 0}
產品中心
{else}
產品中心
{/if}
{* 保留除 page 以外的所有 GET 參數 *}
{assign var="query_params" value=$smarty.get}
{unset $query_params.page}
{assign var="base_query" value=http_build_query($query_params)}
下一頁
{* /zh-tw/product/123 → lang=zh-tw *}
{assign var="segments" value=$current_path|explode:'/'}
{if $segments[1] in ['zh-tw','en','ja']}
{assign var="lang" value=$segments[1]}
{/if}
SERVER_NAME 可能是內網 IP 或 `localhost` → **必須用 `HTTP_HOST`**HTTPS 可能為空 → 檢查 `HTTP_X_FORWARDED_PROTO` 或 `HTTP_CF_VISITOR`<?php
// PHP 端統一處理代理頭
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$_SERVER['HTTPS'] = ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ? 'on' : 'off';
}
if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
$_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
}
{* 防 XSS *}
{$current_url|escape:'html'}
{$current_url|escape:'url'} {* 用於 href/src *}
{$current_url|escape:'javascript'} {* 用於 inline JS *}
最佳實踐:在 PHP 端用統一函數組裝好 `current_url`、`current_path`、`current_host` 等變數傳給 Smarty,模板只負責顯示。避免在模板中寫複雜邏輯,違反 MVC 分層,且難以單元測試。