
PHP cannot directly access the browser’s address bar URL due to server-side execution constraints, but you can reconstruct the full canonical URL (e.g., https://www.example.com/page/some-page/) using $_SERVER superglobal variables — especially when dealing with rewritten URLs via .htaccess.
php cannot directly access the browser’s address bar url due to server-side execution constraints, but you can reconstruct the full canonical url (e.g., `https://www.example.com/page/some-page/`) using `$_server` superglobal variables — especially when dealing with rewritten urls via `.htaccess`.
When Apache rewrites a clean URL like /page/some-page/ to an internal script such as page.php, $_SERVER['REQUEST_URI'] still reflects the original requested path — not the rewritten filename. So if your .htaccess rule is correctly configured (e.g., RewriteRule ^page/(.*)$ page.php?slug=$1 [L]), then $_SERVER['REQUEST_URI'] will indeed return /page/some-page/, not page.php.
However, $_SERVER['REQUEST_URI'] alone only gives the path and query string — not the protocol or domain. To build the complete browser-visible URL, combine it with other reliable $_SERVER values:
<?php // Safely construct the full current URL $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; $host = $_SERVER['HTTP_HOST'] ?? ''; $request_uri = $_SERVER['REQUEST_URI'] ?? '/'; $url = $scheme . '://' . $host . $request_uri; echo htmlspecialchars($url, ENT_QUOTES, 'UTF-8'); ?>
✅ Key points:
-
$_SERVER['HTTP_HOST']contains the host (e.g.,www.example.com) — notSERVER_NAME, which may reflect the server config, not the requested domain. -
$_SERVER['REQUEST_URI']preserves the original rewritten path — crucial for SEO-friendly or RESTful routes. - Always validate or sanitize output (e.g.,
htmlspecialchars()) before echoing in HTML contexts. - Avoid relying on
$_SERVER['PHP_SELF']or$_SERVER['SCRIPT_NAME']— they return the resolved script path, not the browser URL.
⚠️ Caveat: This reconstruction assumes standard HTTP(S) headers. In reverse-proxy setups (e.g., Nginx + Apache, or cloud load balancers), HTTPS and HTTP_HOST may be unreliable — consider checking $_SERVER['HTTP_X_FORWARDED_PROTO'] and $_SERVER['HTTP_X_FORWARDED_HOST'] if trusted proxies are in place, but only after proper validation to prevent host header injection.
In summary: use $_SERVER['REQUEST_URI'] for the path, enrich it with HTTP_HOST and protocol detection, and always treat external $_SERVER data with appropriate validation and escaping.
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











