2023-04-22 08:00:05

获取完整的PHP URL

我使用这段代码来获得完整的URL:

$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

问题是我在我的.htaccess中使用了一些掩码,所以我们在URL中看到的并不总是文件的真实路径。

我需要的是得到URL, URL中写了什么,不多不少——完整的URL。

我需要得到它如何出现在web浏览器的导航栏,而不是服务器上文件的真实路径。


当前回答

使用这一行程序来查找父文件夹URL(如果您无法访问pecl_http附带的http_build_url()):

$url = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://').$_SERVER['SERVER_NAME'].str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname(dirname(__FILE__)));

其他回答

这对HTTP和HTTPS都有效。

echo 'http' . (($_SERVER['HTTPS'] == 'on') ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

输出如下所示。

https://example.com/user.php?token=3f0d9sickc0flmg8hnsngk5u07&access_level=application

看一下$_SERVER['REQUEST_URI'],即

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

(注意双引号字符串语法是完全正确的)

如果你想同时支持HTTP和HTTPS,你可以使用

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

编者注:使用此代码具有安全隐患。客户端可以将HTTP_HOST和REQUEST_URI设置为它想要的任意值。

Use:

$base_dir = __DIR__; // Absolute path to your installation, ex: /var/www/mywebsite
$doc_root = preg_replace("!{$_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']); # ex: /var/www
$base_url = preg_replace("!^{$doc_root}!", '', $base_dir); # ex: '' or '/mywebsite'
$base_url = str_replace('\\', '/', $base_url);//On Windows
$base_url = str_replace($doc_root, '', $base_url);//On Windows
$protocol = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$port = $_SERVER['SERVER_PORT'];
$disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";
$domain = $_SERVER['SERVER_NAME'];
$full_url = "$protocol://{$domain}{$disp_port}{$base_url}"; # Ex: 'http://example.com', 'https://example.com/mywebsite', etc. 

来源:PHP文档根,路径和URL检测

你可以使用不带参数的http_build_url来获取当前页面的完整URL:

$url = http_build_url();

使用这一行程序来查找父文件夹URL(如果您无法访问pecl_http附带的http_build_url()):

$url = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://').$_SERVER['SERVER_NAME'].str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname(dirname(__FILE__)));