PHP_SELF、SCRIPT_NAME与REQUEST_URI概述
$_SERVER[PHP_SELF]、$_SERVER[SCRIPT_NAME]以及$_SERVER['REQUEST_URI']在功能上具有相似性,它们均用于获取与当前访问页面相关的地址信息。为了帮助开发者选择最适合脚本需求的变量,以下将列举相关示例进行对比说明。
关于$_SERVER['PHP_SELF']
复制代码 代码如下: http://www.yoursite.com/example/ — – — /example/index.php http://www.yoursite.com/example/index.php — – — /example/index.php http://www.yoursite.com/example/index.php?a=test — – — /example/index.php http://www.yoursite.com/example/index.php/dir/test — – — /dir/test
当使用$_SERVER['PHP_SELF']时,无论访问的URL是否显式包含index.php,它都会自动返回index.php。然而,如果在文件名后添加斜杠,该变量会将斜杠后的所有内容一并返回到$_SERVER['PHP_SELF']中。
关于$_SERVER['REQUEST_URI']
复制代码 代码如下: http://www.yoursite.com/example/ — – — / http://www.yoursite.com/example/index.php — – — /example/index.php http://www.yoursite.com/example/index.php?a=test — – — /example/index.php?a=test http://www.yoursite.com/example/index.php/dir/test — – — /example/index.php/dir/test
$_SERVER['REQUEST_URI']返回的是URL中精确写入的地址内容。如果URL仅指定到根目录“/”,则该变量直接返回“/”。
关于$_SERVER['SCRIPT_NAME']
复制代码 代码如下: http://www.yoursite.com/example/ — – — /example/index.php http://www.yoursite.com/example/index.php — – — /example/index.php http://www.yoursite.com/example/index.php — – — /example/index.php http://www.yoursite.com/example/index.php/dir/test — – — /example/index.php
在所有返回结果中,该变量始终显示当前的文件名,例如/example/index.php。