PHP 中有许多路径变量,先来认识清楚。假定浏览器中输入的 URL 地址为
http://example.com:8000/aaa/index.php/bbb/ccc?q=ddd
利用下面这些变量可以得到所访问服务器的基本信息:
$_SERVER['SERVER_PROTOCOL'] | 'HTTP 1.0' |
$_SERVER['HTTP_HOST'] | 'example.com' |
$_SERVER['SERVER_PORT'] | '8000' |
利用下面这些变量可以得到所访问路径的基本信息:
$_SERVER['REQUEST_URI'] | '/aaa/index.php/bbb/ccc?q=ddd' |
$_SERVER['PHP_SELF"'] | '/aaa/index.php/bbb/ccc' |
$_SERVER['SCRIPT_NAME'] | '/aaa/index.php' |
$_SERVER['PATH_INFO'] | '/bbb/ccc' |
$_SERVER['QUERY_STRING'] | 'q=ddd' |
利用下面这些变量可以得到 PHP 文件在服务器的路径信息:
__FILE__ | '/home/example/public_html/aaa/index.php' |
$_SERVER['SCRIPT_FILENAME'] | '/home/example/public_html/aaa/index.php' |
$_SERVER['PATH_TRANSLATED'] | '/home/example/public_html/aaa/index.php' |
$_SERVER['DOCUMENT_ROOT'] | '/home/example/public_html' |
如果有 URL rewrite,情况将有所不同。比如 Apache 将 /aaa/index.php 重定向到 /aaa/error.php 时,$_SERVER['SCRIPT_NAME'] 将变成 '/aaa/error.php'。
参考资料:
[1] PHP: $_SERVER - Manual
[2] RFC 3875 - The Common Gateway Interface (CGI) Version 1.1
[3] http - PHP_SELF vs PATH_INFO vs SCRIPT_NAME vs REQUEST_URI - Stack Overflow
[4] url rewriting - Pros/cons of using index.php?q=path/ instead of index.php/path/? - Stack Overflow
[5] How to create friendly URL in php? - Stack Overflow
[6] PHP Get the Full URL - Stack Overflow
[7] PHP get current page URL
[8] URL Rewriting for Beginners - Web Development in Brighton - Added Bytes