您需要$_SERVER['REQUEST_URI']
而不是$_SERVER['SCRIPT_NAME']
,cos$_SERVER['SCRIPT_NAME']
将始终为您提供当前正在工作的文件。
从手册:
SCRIPT_NAME:包含当前脚本的路径。这对于需要指向自身的页面很有用。该__FILE__
常量包含当前(即包含的)文件的完整路径和文件名。.
我想这可以帮助您完全获取当前 URL。
echo 'http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
注意:不要依赖客户的HTTP_HOST
,而是使用SERVER_NAME
!SEE:PHP 中的 HTTP_HOST 和 SERVER_NAME 有什么区别?
安全警告
如果您在任何地方使用它(打印或存储在数据库中),您需要过滤(清理)$_SERVER['REQUEST_URI']
,因为它不安全。
// ie: this could be harmfull
/user?id=123%00%27<script...
因此,请始终在使用用户输入之前对其进行过滤。至少使用htmlspecialchars
,htmlentities
等strip_tags
。
或类似的东西;
function get_current_url($strip = true) {
static $filter, $scheme, $host, $port;
if ($filter == null) {
$filter = function($input) use($strip) {
$input = trim($input);
if ($input == '/') {
return $input;
}
// add more chars if needed
$input = str_ireplace(["\0", '%00', "\x0a", '%0a', "\x1a", '%1a'], '',
rawurldecode($input));
// remove markup stuff
if ($strip) {
$input = strip_tags($input);
}
// or any encoding you use instead of utf-8
$input = htmlspecialchars($input, ENT_QUOTES, 'utf-8');
return $input;
};
$scheme = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME']
: ('http'. (($_SERVER['SERVER_PORT'] == '443') ? 's' : ''));
$host = $_SERVER['SERVER_NAME'];
$port = ($_SERVER['SERVER_PORT'] != '80' && $scheme != 'https')
? (':'. $_SERVER['SERVER_PORT']) : '';
}
}
return sprintf('%s://%s%s%s', $scheme, $host, $port, $filter($_SERVER['REQUEST_URI']));
}