获取PHP中的完整URL


977

我使用以下代码来获取完整的URL:

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

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

我需要的是获取URL,写在URL中的内容,仅此而已-完整的URL。

我需要了解它在Web浏览器的导航栏中的显示方式,而不是服务器上文件的真实路径。


24
@Brade URL栏位于用户浏览器上,那么PHP为什么对此具有任何功能?PHP是服务器端。
2013年

33
@eis相信我,有很多理由想要这个。使用相同模板但需要单独跟踪的登录页面等。事实是PHP(或任何服务器端lang)可以返回URL的所有各个部分,但似乎从来没有在一个字符串中提供全部内容。好像很蠢。
Brade 2013年

12
整个事情永远都不会发送到服务器端,因为这无关紧要,这就是为什么它在任何地方都不可用的原因。我认为任何功能都依赖于该功能。但那只是我的个人意见。
2013年

5
我上面的示例中需要一个自我URL:“填写FORM操作URL”可能是错误的,因为PHP_SELF(仅路径,无域等)足以满足要求。但这并不一定意味着规范自我URL的所有其他需求都是无效的。如果确实如此,那么彻底了解其原因将是非常棒的。
Sz。

4
您不应该在config中对URL进行硬编码的原因之一是当您有安装项目(开发,集成,生产)的不同平台时。它们中的每一个都有其特定的URL,并且您不想根据安装项目的服务器来更改代码。
Guillaume Fache

Answers:


2050

看一下$_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设置为所需的任意值。


134
如果您使用的是https链接怎么办?如果HTTP_HOST不可用或已被客户端篡改怎么办?这个答案似乎不完整且不可靠。
Manachi 2013年

21
您对此无能为力,这是解决所提出问题的正确方法。
Mfoo

183
您可以仅添加HTTPS检查:'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}/{$_SERVER['REQUEST_URI']}"
ivkremer 2014年

7
如果要将URL作为链接输出到浏览器,只需关闭http:。看到:stackoverflow.com/questions/4978235
GameCharmer

5
@斧头。你以为你比我多一点?哈哈ok pal。如果您由于使用主持人工具回滚答案而没有足够强烈地表现出自己的傲慢,那么肯定可以在这里充分地表现出来;因此抹黑了您不得不说的其他一切。另外,我没有误会任何事情(您知道他们对假设...的看法),我确切地知道您在做什么,这不是一个好习惯。
是,巴里

416

简短版本,用于在网页上输出链接

$url =  "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

$escaped_url = htmlspecialchars( $url, ENT_QUOTES, 'UTF-8' );
echo '<a href="' . $escaped_url . '">' . $escaped_url . '</a>';

以下是有关//example.com/path/格式的问题和极端情况的更多详细信息

完整版

function url_origin( $s, $use_forwarded_host = false )
{
    $ssl      = ( ! empty( $s['HTTPS'] ) && $s['HTTPS'] == 'on' );
    $sp       = strtolower( $s['SERVER_PROTOCOL'] );
    $protocol = substr( $sp, 0, strpos( $sp, '/' ) ) . ( ( $ssl ) ? 's' : '' );
    $port     = $s['SERVER_PORT'];
    $port     = ( ( ! $ssl && $port=='80' ) || ( $ssl && $port=='443' ) ) ? '' : ':'.$port;
    $host     = ( $use_forwarded_host && isset( $s['HTTP_X_FORWARDED_HOST'] ) ) ? $s['HTTP_X_FORWARDED_HOST'] : ( isset( $s['HTTP_HOST'] ) ? $s['HTTP_HOST'] : null );
    $host     = isset( $host ) ? $host : $s['SERVER_NAME'] . $port;
    return $protocol . '://' . $host;
}

function full_url( $s, $use_forwarded_host = false )
{
    return url_origin( $s, $use_forwarded_host ) . $s['REQUEST_URI'];
}

$absolute_url = full_url( $_SERVER );
echo $absolute_url;

这是的重大修改版本http://snipplr.com/view.php?codeview&id=2734

网址结构:

scheme:// 用户名:密码 @domain:端口/路径?query_string#fragment_id

粗体部分将不包含在功能中

笔记:

  • 此功能不包括username:password来自完整URL或片段(哈希)的内容。
  • 它不会显示HTTP的默认端口80和HTTPS的端口443。
  • 仅使用http和https方案进行了测试。
  • #fragment_id不是由客户端(浏览器)发送到服务器并不会被添加到完整的URL。
  • $_GET仅包含foo=bar2的网址/example?foo=bar1&foo=bar2
  • 某些CMS和环境将重写$_SERVER['REQUEST_URI']并返回/example?foo=bar2URL,例如在这种情况下/example?foo=bar1&foo=bar2使用$_SERVER['QUERY_STRING']
  • 请记住,URI = URL + URN,但由于流行用法,URL现在同时表示URI和URL。
  • HTTP_X_FORWARDED_HOST如果您不打算使用代理或平衡器,则应删除。
  • 规范说,Host标题必须包含端口号,除非它是缺省值。

客户端(浏览器)控制的变量:

  • $_SERVER['REQUEST_URI']。发送任何不受支持的字符之前,浏览器会对其进行编码。
  • $_SERVER['HTTP_HOST']并且根据PHP手册中的注释,并非总是可用:http : //php.net/manual/en/reserved.variables.php
  • $_SERVER['HTTP_X_FORWARDED_HOST']由平衡器设置,$_SERVER在PHP手册的变量列表中未提及。

服务器控制的变量:

  • $_SERVER['HTTPS']。客户端选择使用此选项,但是服务器返回空或“开”的实际值。
  • $_SERVER['SERVER_PORT']。服务器仅接受允许的数字作为端口。
  • $_SERVER['SERVER_PROTOCOL']。服务器仅接受某些协议。
  • $_SERVER['SERVER_NAME']。根据kralyk,它是在服务器配置中手动设置的,不适用于IPv6 。

有关:

HTTP_HOST vs. SERVER_NAME
HTTP“主机”标头参数中是否需要端口号?
https://stackoverflow.com/a/28049503/175071


14
如果服务器由IPv6 IP地址指定,则此代码将失败。要解决此问题,请将SERVER_NAME替换为HTTP_HOST。
kralyk 2012年

1
注意:$_SERVER['REQUEST_URI']将显示/example?foo=bar2网址,例如/example?foo=bar1&foo=bar2
Timo Huovinen

2
这将不包含#后定义的东西,那些未通过传递到服务器
威廉国王

1
我不确定这是否没有安全风险。在您的示例中,您可以发送Host标头到达正确的页面,但可以让页面认为使用HTTP_X_FORWARDED_HOST标头通过另一个主机调用了该页面。当应用程序使用此信息时(无论如何),这确实可能是一个安全问题,因为它使您可以保证情况并非如此。
hek2mgl 2013年

1
@ Matt3o12端口的值直接从Host标头获取,尚未看到如此设置,感谢您提及它,它将添加为调整项
Timo Huovinen 2014年

226

例如: https://(www.)example.com/subFolder/myfile.php?var=blabla#555

// ======= PATHINFO ====== //
$x = pathinfo($url);
$x['dirname']      🡺 https://example.com/subFolder
$x['basename']     🡺                               myfile.php?var=blabla#555 // Unsecure! 
$x['extension']    🡺                                      php?var=blabla#555 // Unsecure! 
$x['filename']     🡺                               myfile

// ======= PARSE_URL ====== //
$x = parse_url($url);
$x['scheme']       🡺 https
$x['host']         🡺         example.com
$x['path']         🡺                    /subFolder/myfile.php
$x['query']        🡺                                          var=blabla
$x['fragment']     🡺                                                     555

//=================================================== //
//========== self-defined SERVER variables ========== //
//=================================================== //
$_SERVER["DOCUMENT_ROOT"]  🡺 /home/user/public_html
$_SERVER["SERVER_ADDR"]    🡺 143.34.112.23
$_SERVER["SERVER_PORT"]    🡺 80(or 443 etc..)
$_SERVER["REQUEST_SCHEME"] 🡺 https                                         //similar: $_SERVER["SERVER_PROTOCOL"] 
$_SERVER['HTTP_HOST']      🡺         example.com (or with WWW)             //similar: $_SERVER["ERVER_NAME"]
$_SERVER["REQUEST_URI"]    🡺                       /subFolder/myfile.php?var=blabla
$_SERVER["QUERY_STRING"]   🡺                                             var=blabla
__FILE__                   🡺 /home/user/public_html/subFolder/myfile.php
__DIR__                    🡺 /home/user/public_html/subFolder              //same: dirname(__FILE__)
$_SERVER["REQUEST_URI"]    🡺                       /subFolder/myfile.php?var=blabla
parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)🡺  /subFolder/myfile.php 
$_SERVER["PHP_SELF"]       🡺                       /subFolder/myfile.php

// ==================================================================//
//if "myfile.php" is included in "PARENTFILE.php" , and you visit  "PARENTFILE.PHP?abc":
$_SERVER["SCRIPT_FILENAME"]🡺 /home/user/public_html/parentfile.php
$_SERVER["PHP_SELF"]       🡺                       /parentfile.php
$_SERVER["REQUEST_URI"]    🡺                       /parentfile.php?var=blabla
__FILE__                   🡺 /home/user/public_html/subFolder/myfile.php

// =================================================== //
// ================= handy variables ================= //
// =================================================== //
//If site uses HTTPS:
$HTTP_or_HTTPS = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || $_SERVER['SERVER_PORT']==443) ? 'https://':'http://' );            //in some cases, you need to add this condition too: if ('https'==$_SERVER['HTTP_X_FORWARDED_PROTO'])  ...

//To trim values to filename, i.e. 
basename($url)             🡺 myfile.php

//excellent solution to find origin
$debug_files = debug_backtrace();       
$caller_file = count($debug_files) ? $debug_files[count($debug_files) - 1]['file'] : __FILE__;

注意 !!!

  • #在上面的示例中,仅出于说明目的手动使用了hashtag 部分,但是服务器端语言(包括php)无法本地检测到它们(只有Javascript可以做到这一点,因为hashtag仅是browser/client side功能)。
  • DIRECTORY_SEPARATOR返回\Windows类型的托管,而不是/



对于WordPress

//(let's say, if wordpress is installed in subdirectory:  http://example.com/wpdir/)
home_url()                      🡺 http://example.com/wpdir/        //if is_ssl() is true, then it will be "https"
get_stylesheet_directory_uri()  🡺 http://example.com/wpdir/wp-content/themes/THEME_NAME  [same: get_bloginfo('template_url') ]
get_stylesheet_directory()      🡺 /home/user/public_html/wpdir/wp-content/themes/THEME_NAME
plugin_dir_url(__FILE__)        🡺 http://example.com/wpdir/wp-content/themes/PLUGIN_NAME
plugin_dir_path(__FILE__)       🡺 /home/user/public_html/wpdir/wp-content/plugins/PLUGIN_NAME/  

#部分在哪里,在服务器端#之后我们是否无法访问部分?
罗希特·哈特里

@RohitKhatri那部分只能在浏览器中访问,而不会发送到服务器
beppe9000 19/12/24

用wordpress函数获取带有查询字符串的URL的功能是什么?
beppe9000 '19

64

这是使用三元语句的解决方案,使代码最少:

$url = "http" . (($_SERVER['SERVER_PORT'] == 443) ? "s" : "") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

假设某人的Web服务器使用HTTPS的标准端口443,这是最小且最简单的方法。


18
或用于$_SERVER["HTTPS"] == "on"检查SSL是否打开。
Dzhuneyt

15
您应该使用$ _SERVER [“ HTTPS”],因为端口443仅是默认SSL端口,而不是SSL指示器。
Alex Barker 2013年

4
@AlexBarker-这就是为什么我说“假设某人的Web服务器使用HTTPS的标准端口443”。
honyovk

44

查找当前URL的最喜欢的跨平台方法是:

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

7
关闭,但是我需要将其更改为:$ url =((isset($ _ SERVER ['HTTPS'])&& $ _SERVER ['HTTPS']!=='off')?“ https”:“ http”) 。“://:// $ _ SERVER [HTTP_HOST] $ _SERVER [REQUEST_URI]”;
埃里克·艾伦

34

只需使用:

$uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']

1
就我想使用它而言,它在IIS中不起作用。stackoverflow.com/questions/18008135/...
埃里克·艾伦

它输出什么?
HappyCoder

5
PHP注意:未定义的索引:REQUEST_SCHEME
Erik Allen

我喜欢这个解决方案!但是您也可以使其适用于nginx吗?
cowboysaif '16

1
http://example.com :8080 /request.php失败了 这些答案很复杂是有原因的。
大卫·雷富阿

21
function full_path()
{
    $s = &$_SERVER;
    $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on') ? true:false;
    $sp = strtolower($s['SERVER_PROTOCOL']);
    $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
    $port = $s['SERVER_PORT'];
    $port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
    $host = isset($s['HTTP_X_FORWARDED_HOST']) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
    $host = isset($host) ? $host : $s['SERVER_NAME'] . $port;
    $uri = $protocol . '://' . $host . $s['REQUEST_URI'];
    $segments = explode('?', $uri, 2);
    $url = $segments[0];
    return $url;
}

注意:我只是对Timo Huovinen的代码进行了更新,因此您不会在URL中获得任何GET参数。该网址是简单的,删除了类似?hi=i&am=a&get

例:

http://www.example.com/index?get=information

将显示为:

http://www.example.com/index

除非您使用GET参数来定义一些特定的内容,否则就可以使用他的代码!:-)


嘿,很酷:)您也可以删除“#”(URL片段)后的任何内容,以防它以某种方式滑入
Timo Huovinen 2012年

并非如此,因为如果在“ explode('#',$ segment [0])中进行设置,它将被视为错误,因为”#“符号会破坏URL,并且只能由Javascript读取。但是,可以肯定的是,您可以使用“ return trim($ url,'#');”来重新制作“ return $ url;”,因为那样的话您将删除它,以防它在那里。但是它不会删除以下内容。您可以根据需要阅读“ Parse_url”。:-)
Alex Westergaard,2012年

17

适用于所有网络服务器(Apache,nginx,IIS等)的清晰代码:

$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

11

这是我的解决方案-代码受Tracy Debugger启发。已更改为支持不同的服务器端口。您可以获得完整的当前URL,包括$_SERVER['REQUEST_URI']或仅包含基本服务器URL。检查我的功能:

function getCurrentUrl($full = true) {
    if (isset($_SERVER['REQUEST_URI'])) {
        $parse = parse_url(
            (isset($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https://' : 'http://') .
            (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '')) . (($full) ? $_SERVER['REQUEST_URI'] : null)
        );
        $parse['port'] = $_SERVER["SERVER_PORT"]; // Setup protocol for sure (80 is default)
        return http_build_url('', $parse);
    }
}

这是测试代码:

// Follow $_SERVER variables was set only for test
$_SERVER['HTTPS'] = 'off'; // on
$_SERVER['SERVER_PORT'] = '9999'; // Setup
$_SERVER['HTTP_HOST'] = 'some.crazy.server.5.name:8088'; // Port is optional there
$_SERVER['REQUEST_URI'] = '/150/tail/single/normal?get=param';

echo getCurrentUrl();
// http://some.crazy.server.5.name:9999/150/tail/single/normal?get=param

echo getCurrentUrl(false);
// http://some.crazy.server.5.name:9999/

注意:http_build_url需要安装pecl_http
Mauran Muthiah

11

HTTP_HOST和REQUEST_URI必须用引号引起来,否则它将在PHP 7.2中引发错误

采用:

$actual_link = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

如果要同时支持HTTP和HTTPS:

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

9

与接受的答案相同的技术,但是具有HTTPS支持,并且更具可读性:

$current_url = sprintf(
    '%s://%s/%s',
    isset($_SERVER['HTTPS']) ? 'https' : 'http',
    $_SERVER['HTTP_HOST'],
    $_SERVER['REQUEST_URI']
);

9

我已经使用此函数来处理URL:

 <?php
     function curPageURL()
     {
         $pageURL = 'http';
         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
         $pageURL .= "://";
         if ($_SERVER["SERVER_PORT"] != "80") {
             $pageURL .=
             $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
         }
         else {
             $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
         }
         return $pageURL;
     }
 ?>

7

使用此单行代码查找父文件夹URL(如果您无权访问pecl_http附带的http_build_url()):

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

5
您将URL和文件的绝对位置混合在磁盘上
sd1sd1

6

使用Apache环境变量很容易做到这一点。这仅适用于Apache 2,我假设您正在使用。

只需使用以下PHP代码:

<?php
    $request_url = apache_getenv("HTTP_HOST") . apache_getenv("REQUEST_URI");
    echo $request_url;
?>

6

尝试这个:

print_r($_SERVER);

$_SERVER是一个包含标题,路径和脚本位置等信息的数组。该数组中的条目由Web服务器创建。不能保证每个Web服务器都可以提供其中的任何一个。服务器可能会省略某些服务器,或提供此处未列出的其他服务器。就是说,在»CGI / 1.1规范中考虑了很多这些变量,因此您应该可以期待这些变量。

$HTTP_SERVER_VARS包含相同的初始信息,但不是超全局信息。(请注意,$HTTP_SERVER_VARS$_SERVER是不同的变量,PHP照这样处理它们)



5

我已经制作了此类来处理我的URI

<?php
/** -------------------------------------------------------------------------------------------------------------------
 * URI CLASS
 * URI management class
 *
 * @author Sandu Liviu Catalin
 * @email slc(dot)universe(at)gmail(dot)com
 * @license Public Domain
**/
abstract class _URI
{
    /** ---------------------------------------------------------------------------------------------------------------
     *  - BASE PARAMETERS
     * $_Script_Hidden - Hide the script name from the returned URI
     * $_Public_Path - Location where public resources are stored
     * $_Public_Relative - Return the relative path version of public location
     * $_Public_Skin - Is the skin directory located in the public directory
     * $_Skin_Path - Location where skins are stored
     * $_Skin_Relative - Return the relative path version of skin location
     * $_Skin_Default - Use this as the default system skin
     * $_Fallback_Base - Use this base URL if you can't extract the current URL
     * $_Fallback_Scheme - Use this scheme if you can't find it automatically
     * $_Fallback_User - Use this user name if you can't find it automatically
     * $_Fallback_Passwd - Use this password if you can't find it automatically
     * $_Fallback_Host - Use this host if you can't find it automatically
     * $_Fallback_Port - Use this port number if you can't find it automatically
     * $_Fallback_Script - Use this script name if you can't find it automatically
     * $_Separator_Scheme - Use this to separate the scheme from the rest of the url
     * $_Separator_Credentials - Use this to separate the user name from the password
     * $_Separator_Auth - Use this to separate the user name and password from host
     * $_Separator_Port - Use this to separate the port number from host
     * $_Separator_Query - Use this to separate the query data from base URL
     * $_Separator_Fragment - Use this to separate the fragment data from query data
    */
    protected static $_Script_Hidden;
    protected static $_Public_Path;
    protected static $_Public_Relative;
    protected static $_Public_Skin;
    protected static $_Skin_Path;
    protected static $_Skin_Relative;
    protected static $_Skin_Default;
    protected static $_Fallback_Base;
    protected static $_Fallback_Scheme;
    protected static $_Fallback_User;
    protected static $_Fallback_Passwd;
    protected static $_Fallback_Host;
    protected static $_Fallback_Port;
    protected static $_Fallback_Script;
    protected static $_Separator_Scheme;
    protected static $_Separator_Credentials;
    protected static $_Separator_Auth;
    protected static $_Separator_Port;
    protected static $_Separator_Query;
    protected static $_Separator_Fragment;

    /** ----------------------------------------------------------------------------------------------------------------
     * CACHED BASES
     * Precompiled common URLs for quick retrieval
    */
    protected static $Base_Host;
    protected static $Base_App;
    protected static $Base_Script;
    protected static $Base_Current;
    protected static $Base_Public;
    protected static $Base_Skin;

    /** ----------------------------------------------------------------------------------------------------------------
     * DATA CONTAINERS
     * Raw URI segments saved from extracted data
    */
    protected static $__Segments = array(
        'SCHEME' => '',
        'USER' => '',
        'PASSWD' => '',
        'HOST' => '',
        'PORT' => '',
        'PATH' => '',
        'SCRIPT' => '',
        'INFO' => '',
        'QUERY' => '',
    );

    /** ----------------------------------------------------------------------------------------------------------------
     * PARSER KEYWORDS
     * URI data asigned to specific keywords.
    */
    protected static $__Parsers;

    /** ----------------------------------------------------------------------------------------------------------------
     * CLASS INITIALIZER
     * Initialize the class
     *
     * @access public
     * @param $Params [array] - An associative array of supported parrameters
     * @return void
    */
    public static function __Init($Params=array())
    {
        // Configure the class
        self::$_Script_Hidden = (isset($Params['Script_Hidden'])) ? $Params['Script_Hidden'] : FALSE;
        self::$_Public_Path = (isset($Params['Public_Path'])) ? $Params['Public_Path'] : 'public';
        self::$_Public_Relative = (isset($Params['Public_Relative'])) ? $Params['Public_Relative'] : TRUE;
        self::$_Public_Skin = (isset($Params['Public_Skin'])) ? $Params['Public_Skin'] : TRUE;
        self::$_Skin_Path = (isset($Params['Skin_Path'])) ? $Params['Skin_Path'] : 'themes';
        self::$_Skin_Relative = (isset($Params['Skin_Relative'])) ? $Params['Skin_Relative'] : TRUE;
        self::$_Skin_Default = (isset($Params['Skin_Default'])) ? $Params['Skin_Default'] : 'default';
        self::$_Fallback_Base = (isset($Params['Fallback_Base'])) ? $Params['Fallback_Base'] : '127.0.0.1';
        self::$_Fallback_Scheme = (isset($Params['Fallback_Scheme'])) ? $Params['Fallback_Scheme'] : 'http';
        self::$_Fallback_User = (isset($Params['Fallback_User'])) ? $Params['Fallback_User'] : '';
        self::$_Fallback_Passwd = (isset($Params['Fallback_Passwd'])) ? $Params['Fallback_Passwd'] : '';
        self::$_Fallback_Host = (isset($Params['Fallback_Host'])) ? $Params['Fallback_Host'] : '127.0.0.1';
        self::$_Fallback_Port = (isset($Params['Fallback_Port'])) ? $Params['Fallback_Port'] : '';
        self::$_Fallback_Script = (isset($Params['Fallback_Script'])) ? $Params['Fallback_Script'] : 'index.php';
        self::$_Separator_Scheme = (isset($Params['Separator_Scheme'])) ? $Params['Separator_Scheme'] : '://';
        self::$_Separator_Credentials = (isset($Params['Separator_Credentials'])) ? $Params['Separator_Credentials'] : ':';
        self::$_Separator_Auth = (isset($Params['Separator_Auth'])) ? $Params['Separator_Auth'] : '@';
        self::$_Separator_Port = (isset($Params['Separator_Port'])) ? $Params['Separator_Port'] : ':';
        self::$_Separator_Query = (isset($Params['Separator_Query'])) ? $Params['Separator_Query'] : '?';
        self::$_Separator_Fragment = (isset($Params['Separator_Fragment'])) ? $Params['Separator_Fragment'] : '#';
        // Do some clean up of the configurations
        self::$_Public_Path = implode('/', explode('/', str_replace(array('/', '\\'), '/', self::$_Public_Path)));
        self::$_Skin_Path = implode('/', explode('/', str_replace(array('/', '\\'), '/', self::$_Skin_Path)));
        // Extract the URL information
        self::Extract();
        // Precompile common bases
        self::$Base_Host = self::Compile('HOST');
        self::$Base_App = self::Compile('PATH');
        self::$Base_Script = self::$Base_App.(self::$_Script_Hidden ? '' : '/'.self::$__Segments['SCRIPT']);
        self::$Base_Current = self::$Base_Script.(empty(self::$__Segments['INFO']) ? '' : '/'.self::$__Segments['INFO']);
        self::$Base_Public = self::$_Public_Relative ? self::$_Public_Path : self::$Base_App.'/'.self::$_Public_Path;
        self::$Base_Skin = self::$_Skin_Relative ? self::$_Skin_Path : self::$Base_Public.'/'.self::$_Skin_Path;
        self::$Base_Skin .= '/'.self::$_Skin_Default;
        // Setup the parsers
        self::$__Parsers['SR_Key'][] = '%HostBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Host;
        self::$__Parsers['SR_Key'][] = '%AppBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_App;
        self::$__Parsers['SR_Key'][] = '%ScriptBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Script;
        self::$__Parsers['SR_Key'][] = '%CurrentBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Current;
        self::$__Parsers['SR_Key'][] = '%PublicBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Public;
        self::$__Parsers['SR_Key'][] = '%SkinBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Skin;
        self::$__Parsers['SR_Data'][] =& self::$__Segments['SCHEME'];
        self::$__Parsers['SR_Key'][] = '%UserSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['USER'];
        self::$__Parsers['SR_Key'][] = '%PasswdSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['PASSWD'];
        self::$__Parsers['SR_Key'][] = '%HostSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['HOST'];
        self::$__Parsers['SR_Key'][] = '%PortSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['PORT'];
        self::$__Parsers['SR_Key'][] = '%PathSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['PATH'];
        self::$__Parsers['SR_Key'][] = '%ScriptSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['SCRIPT'];
        self::$__Parsers['SR_Key'][] = '%InfoSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['INFO'];
        self::$__Parsers['SR_Key'][] = '%QuerySegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['QUERY'];
        self::$__Parsers['SR_Key'][] = '%PublicPath%';
        self::$__Parsers['SR_Data'][] =& self::$_Public_Path;
        self::$__Parsers['SR_Key'][] = '%SkinPath%';
        self::$__Parsers['SR_Data'][] =& self::$_Skin_Path;
        self::$__Parsers['SR_Key'][] = '%DefaultSkin%';
        self::$__Parsers['SR_Data'][] =& self::$_Skin_Default;
        // Everything OK so far
    }

    /** ----------------------------------------------------------------------------------------------------------------
     * URI EXTRACTOR
     * Try every posibility to obtain all the segments of the current URL
     *
     * @access public
     * @return array
    */
    public static function Extract()
    {
        // No point in executing twice to get the same result
        if (!empty(self::$__Segments['HOST'])) return self::$__Segments;
        // Let's try to have a falback for most basic data
        $Script_URI = (isset($_SERVER['SCRIPT_URI'])) ? parse_url($_SERVER['SCRIPT_URI']) : array();
        if (empty($Script_URI)) {
            $Script_URI = parse_url(self::$_Fallback_Base);
        }
        // Try ever possibility to obtain the data that surounds the script name
        if (isset($_SERVER['PHP_SELF'])) {
            $Script_Path = $_SERVER['PHP_SELF'];
        } elseif (isset($_SERVER['REQUEST_URI'])) {
            $Script_Path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
        } elseif (isset($Script_URI['path'])) {
            $Script_Path = $Script_URI['path'];
        } elseif (isset($_SERVER['SCRIPT_NAME'])) {
            $Script_Path = isset($_SERVER['SCRIPT_NAME']).(isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '');
        } elseif (isset($_SERVER['DOCUMENT_ROOT']) && isset($_SERVER['SCRIPT_FILENAME'])) {
            $Script_Path = substr($_SERVER['SCRIPT_FILENAME'], strlen($_SERVER['DOCUMENT_ROOT']),
                                    (strlen($_SERVER['SCRIPT_FILENAME'])-strlen($_SERVER['DOCUMENT_ROOT'])));
            $Script_Path .= (isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '');
        } else {
            $Script_Path = '';
        }
        // Explode the previously extracted data
        if (strlen($Script_Path) > 0) {
            $Script_Path = preg_split('/[\/]/', $Script_Path, -1, PREG_SPLIT_NO_EMPTY);
        } else {
            $Script_Path = array();
        }
        // Try to obtain the name of the currently executed script
        if (isset($_SERVER['SCRIPT_FILENAME'])) {
            $Script_Name = basename($_SERVER['SCRIPT_FILENAME']);
        } elseif (isset($_SERVER['SCRIPT_NAME'])) {
            $Script_Name = basename($_SERVER['SCRIPT_NAME']);
        } else {
            $Script_Name = self::$_Fallback_Script;
        }
        // Try to find the name of the script in the script path
        $Script_Split = (is_string($Script_Name)) ? array_search($Script_Name, $Script_Path, TRUE) : NULL;
        // Try to obtain the request scheme
        if (isset($_SERVER['REQUEST_SCHEME'])) {
            self::$__Segments['SCHEME'] = $_SERVER['REQUEST_SCHEME'];
        } elseif (isset($_SERVER['SERVER_PROTOCOL'])) {
            self::$__Segments['SCHEME'] = strtolower($_SERVER['SERVER_PROTOCOL']);
            self::$__Segments['SCHEME'] = substr(self::$__Segments['SCHEME'], 0, strpos(self::$__Segments['SCHEME'], '/'));
            self::$__Segments['SCHEME'] .= (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 's' : '';
        } elseif (isset($Script_URI['scheme'])) {
            self::$__Segments['SCHEME'] = $Script_URI['scheme'];
        } else {
            self::$__Segments['SCHEME'] = self::$_Fallback_Scheme;
        }
        // Try to obtain the user name (if one was used)
        if (isset($_SERVER['PHP_AUTH_USER'])) {
            self::$__Segments['USER'] = $_SERVER['PHP_AUTH_USER'];
        } elseif (isset($Script_URI['user'])) {
            self::$__Segments['USER'] = $Script_URI['user'];
        } else {
            self::$__Segments['USER'] = self::$_Fallback_User;
        }
        // Try to obtain the user password (if one was used)
        if (isset($_SERVER['PHP_AUTH_PW'])) {
            self::$__Segments['PASSWD'] = $_SERVER['PHP_AUTH_PW'];
        } elseif (isset($Script_URI['pass'])) {
            self::$__Segments['PASSWD'] = $Script_URI['pass'];
        } else {
            self::$__Segments['PASSWD'] = self::$_Fallback_Passwd;
        }
        // Try to obtai the host name
        if (isset($_SERVER['SERVER_NAME'])) {
            self::$__Segments['HOST'] = $_SERVER['SERVER_NAME'];
        } elseif (isset($_SERVER['HTTP_HOST'])) {
            self::$__Segments['HOST'] = $_SERVER['HTTP_HOST'];
        } elseif (isset($Script_URI['host'])) {
            self::$__Segments['HOST'] = $Script_URI['host'];
        } else {
            self::$__Segments['HOST'] = self::$_Fallback_Host;
        }
        // Try to obtain the port number (if one was used)
        if (isset($Script_URI['port'])) {
            self::$__Segments['PORT'] = $Script_URI['port'];
        } else {
            self::$__Segments['PORT'] = self::$_Fallback_Port;
        }
        // Try to obtain the path to the script
        if (is_numeric($Script_Split)) {
            self::$__Segments['PATH'] = implode('/', array_slice($Script_Path, 0, $Script_Split, TRUE));
        } else {
            self::$__Segments['PATH'] = '';
        }
        // Try to obtain the Script name
        if (is_string($Script_Name)) {
            self::$__Segments['SCRIPT'] = $Script_Name;
        } else {
            self::$__Segments['SCRIPT'] = '';
        }
        // Try to obtain any passed info
        if (isset($_SERVER['PATH_INFO'])) {
            self::$__Segments['INFO'] = implode('/', preg_split('/[\/]/', $_SERVER['PATH_INFO'], -1, PREG_SPLIT_NO_EMPTY));
        } elseif (is_numeric($Script_Split)) {
            self::$__Segments['INFO'] = implode('/', array_slice($Script_Path, $Script_Split+1));
        } else {
            self::$__Segments['INFO'] = '';
        }
        // -----Pending Feature: Try to also extract the query string

        // Return the extracted URI segments
        return self::$__Segments;

    }

    /** ----------------------------------------------------------------------------------------------------------------
     * URI COMPILER
     * Compile raw URI segments into a usable URL
     *
     * @access public
     * @param $Until [string] - The name of the segment where compilation should stop and return
     * @return string
    */
    public static function Compile($Until=NULL)
    {
        $URI= '';
        $Until = (is_string($Until)) ? strtoupper($Until) : $Until;
        if ($Until === 'SCHEME') {
            return $URI .= (self::$__Segments['SCHEME'] !== '') ? self::$__Segments['SCHEME'].self::$_Separator_Scheme : '';
        } else {
            $URI .= (self::$__Segments['SCHEME'] !== '') ? self::$__Segments['SCHEME'].self::$_Separator_Scheme : '';
        }
        if ($Until === 'USER') {
            return $URI .= (self::$__Segments['USER'] !== '') ? self::$__Segments['USER'].self::$_Separator_Credentials : '';
        } else {
            $URI .= (self::$__Segments['USER'] !== '') ? self::$__Segments['USER'] : '';
        }
        $URI .= (self::$__Segments['USER'] !== '' || self::$__Segments['PASSWD'] !== '') ? self::$_Separator_Credentials : '';
        if ($Until === 'PASSWD') {
            return $URI .= (self::$__Segments['PASSWD'] !== '') ? self::$__Segments['PASSWD'].self::$_Separator_Auth : '';
        } else {
            $URI .= (self::$__Segments['PASSWD'] !== '') ? self::$__Segments['PASSWD'] : '';
        }
        $URI .= (self::$__Segments['USER'] !== '' || self::$__Segments['PASSWD'] !== '') ? self::$_Separator_Auth : '';
        if ($Until === 'HOST') {
            return $URI .= (self::$__Segments['HOST'] !== '') ? self::$__Segments['HOST'] : '';
        } else {
            $URI .= (self::$__Segments['HOST'] !== '') ? self::$__Segments['HOST'] : '';
        }
        if ($Until === 'PORT') {
            return $URI .= (self::$__Segments['PORT'] !== '') ? self::$_Separator_Port.self::$__Segments['PORT'] : '';
        } else {
            $URI .= (self::$__Segments['PORT'] !== '') ? self::$_Separator_Port.self::$__Segments['PORT'] : '';
        }
        if ($Until === 'PATH') {
            return $URI .= (self::$__Segments['PATH'] !== '') ? '/'.self::$__Segments['PATH'] : '';
        } else {
            $URI .= (self::$__Segments['PATH'] !== '') ? '/'.self::$__Segments['PATH'] : '';
        }
        if ($Until === 'SCRIPT') {
            return $URI .= (self::$__Segments['SCRIPT'] !== '') ? '/'.self::$__Segments['SCRIPT'] : '';
        } else {
            $URI .= (self::$__Segments['SCRIPT'] !== '') ? '/'.self::$__Segments['SCRIPT'] : '';
        }
        if ($Until === 'INFO') {
            return $URI .= (self::$__Segments['INFO'] !== '') ? '/'.self::$__Segments['INFO'] : '';
        } else {
            $URI .= (self::$__Segments['INFO'] !== '') ? '/'.self::$__Segments['INFO'] : '';
        }
        return $URI;
    }

    /** ----------------------------------------------------------------------------------------------------------------
     * SEGMENT RETRIEVER
     * Return a specific URI segment
     *
     * @access public
     * @param $Name [string] - The name of the segment you want
     * @return string (on success) bool (on failure)
    */
    public static function Segment($Name)
    {
        if (isset(self::$__Segments[$Name])) {
            return self::$__Segments[$Name];
        } return FALSE;
    }

    /** ----------------------------------------------------------------------------------------------------------------
     * BASE RETRIEVER
     * Return a specific precompiled base
     *
     * @access public
     * @param $Name [string] - The name of the base you want
     * @return mixed (on success) boolean (on failure)
    */
    public static function Base($Name)
    {
        switch ($Name) {
            case 'Host':
            case 'Domain':
                return self::$Base_Host;
            break;
            case 'App':
            case 'Base':
                return self::$Base_App;
            break;
            case 'Script':
            case 'Index':
                return self::$Base_Script;
            break;
            case 'Current':
            case 'This':
                return self::$Base_Current;
            break;
            case 'Public':
            case 'Web':
                return self::$Base_Public;
            break;
            case 'Skin':
            case 'Theme':
                return self::$Base_Skin;
            break;
            case 'All':
                return array(
                    'Host'=>self::$Base_Host,
                    'App'=>self::$Base_App,
                    'Script'=>self::$Base_Script,
                    'Current'=>self::$Base_Current,
                    'Public'=>self::$Base_Public,
                    'Skin'=>self::$Base_Skin,
                );
            break;
        } return FALSE;
    }

    /** ----------------------------------------------------------------------------------------------------------------
     * STRING PARSER
     * Replace known keywords in the specified string with current URI data
     *
     * @access public
     * @param $String [string] - A string that you want to parse
     * @return void
    */
    public static function Parse($String)
    {
        if (is_string($String)) {
            return str_replace(self::$__Parsers['SR_Key'], self::$__Parsers['SR_Data'], $String);
        } elseif (is_array($String)) {
            foreach ($String as $K => $V) {
                $Parsed[$K] = self::$replace($V);
            } return $Parsed;
        } return FALSE;
    }
}
if (isset($_URI_Params)) {
    _URI::__Init($_URI_Params);
} else {
    _URI::__Init();
} 

当然,您必须使其适应您的需求和系统!

<?php
// Change a few parameters before loading the class.
$_URI_Params = array(
    'Public_Relative' => FALSE,
    'Skin_Relative' => FALSE,
    'Skin_Default' => 'classic',
    // etc.
);
// Get the URI class
require('uri.php');
// Output all extracted URI segments
echo '<pre>';
var_dump(_URI::Extract());
echo '</pre>';
// Output extracted segments individually
echo 'Scheme: '._URI::Segment('SCHEME').'<br/>';
echo 'User: '._URI::Segment('USER').'<br/>';
echo 'Password: '._URI::Segment('PASSWD').'<br/>';
echo 'Host: '._URI::Segment('HOST').'<br/>';
echo 'Port: '._URI::Segment('PORT').'<br/>';
echo 'Path: '._URI::Segment('PATH').'<br/>';
echo 'Script: '._URI::Segment('SCRIPT').'<br/>';
echo 'Info: '._URI::Segment('INFO').'<br/>';
// Compile extracted segments into a usable URL
echo '<br/>';
echo 'Full Compiled URI: '._URI::Compile().'<br/>';
echo '<br/>';
// Output precompiled common bases for a faster result and better performance
echo 'Host Base: '._URI::Base('Host').'<br/>';
echo 'Application Base: '._URI::Base('App').'<br/>';
echo 'Running Script: '._URI::Base('Script').'<br/>';
echo 'Current URI Base: '._URI::Base('Current').'<br/>';
echo 'Public Folder Base: '._URI::Base('Public').'<br/>';
echo 'Skin Folder Base: '._URI::Base('Skin').'<br/>';
// Get all the precompiled bases in an associative array
echo '<pre>';
var_dump(_URI::Base('All'));
echo '</pre>';
// Parse an example string and replace known keys with actual URI data.
echo _URI::Parse('This is my current domain: %HostBase%
And the current application is here: %AppBase%
I load my skins form: %SkinBase%
etc.
'); 

它仍然需要完善,但这是集中式URI系统的理想解决方案:D


4

这是您的问题的解决方案:

//Fetch page URL by this

$url = $_SERVER['REQUEST_URI'];
echo "$url<br />";

//It will print
//fetch host by this

$host=$_SERVER['HTTP_HOST'];
echo "$host<br />";

//You can fetch the full URL by this

$fullurl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $fullurl;

3

我用了这个说法。

$base = "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]$my_web_base_path";
$url = $base . "/" . dirname(dirname(__FILE__));

我希望这能帮到您。


3
public static function getCurrentUrl($withQuery = true)
{
    $protocol = stripos($_SERVER['SERVER_PROTOCOL'], 'https') === false ? 'http' : 'https';
    $uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

    return $withQuery ? $uri : str_replace('?' . $_SERVER['QUERY_STRING'], '', $uri);
}

2

我使用了下面的代码,对于我来说,无论是HTTP还是HTTPS,它都可以正常工作。

function curPageURL() {
  if(isset($_SERVER["HTTPS"]) && !empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] != 'on' )) {
        $url = 'https://'.$_SERVER["SERVER_NAME"];//https url
  }  else {
    $url =  'http://'.$_SERVER["SERVER_NAME"];//http url
  }
  if(( $_SERVER["SERVER_PORT"] != 80 )) {
     $url .= $_SERVER["SERVER_PORT"];
  }
  $url .= $_SERVER["REQUEST_URI"];
  return $url;
}

echo curPageURL();

演示版


http和https的互换位置。
Shwet

除非我没有记错,否则$_SERVER['HTTPS'] = 'off'将触发HTTPS路径。那似乎不对。另一方面,我也不认为原来的逻辑是正确的。
NisseEngström'2

2
$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. 

来源:http//blog.lavoie.sl/2013/02/php-document-root-path-and-url-detection.html


2

这是使用PHP的filter_input函数的更安全版本的可接受答案的基础,该函数还弥补了可能的不足$_SERVER['REQUEST_URI']

$protocol_https = filter_input(INPUT_SERVER, 'HTTPS', FILTER_SANITIZE_STRING);
$host = filter_input(INPUT_SERVER, 'HTTP_HOST', FILTER_SANITIZE_URL);
$request_uri = filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL);
if(strlen($request_uri) == 0)
{
    $request_uri = filter_input(INPUT_SERVER, 'SCRIPT_NAME', FILTER_SANITIZE_URL);
    $query_string = filter_input(INPUT_SERVER, 'QUERY_STRING', FILTER_SANITIZE_URL);
    if($query_string)
    {
        $request_uri .= '?' . $query_string;
    }
}
$full_url = ($protocol_https ? 'https' : 'http') . '://' . $host . $request_uri;

您可以使用一些不同的过滤器根据自己的喜好进行调整。


1

您可以HTTP_ORIGIN按照以下代码段所示进行使用:

if ( ! array_key_exists( 'HTTP_ORIGIN', $_SERVER ) ) {
    $this->referer = $_SERVER['SERVER_NAME'];
} else {
    $this->referer = $_SERVER['HTTP_ORIGIN'];
}

1

使用非常简单:

function current_url() {
    $current_url  = ( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
    $current_url .= ( $_SERVER["SERVER_PORT"] != 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
    $current_url .= $_SERVER["REQUEST_URI"];

    return $current_url;
}

2
嗨,鉴于此页面上已经有多少个答案,您能否添加一些解释以说明为什么它比其他方法更好,或者它有什么不同之处?
IMSoP

0

我认为这种方法很好..尝试一下

if($_SERVER['HTTP_HOST'] == "localhost"){
    define('SITEURL', 'http://' . $_SERVER['HTTP_HOST']);
    define('SITEPATH', $_SERVER['DOCUMENT_ROOT']);
    define('CSS', $_SERVER['DOCUMENT_ROOT'] . '/css/');
    define('IMAGES', $_SERVER['DOCUMENT_ROOT'] . '/images/');
}
else{
    define('SITEURL', 'http://' . $_SERVER['HTTP_HOST']);
    define('SITEPATH', $_SERVER['DOCUMENT_ROOT']);
    define('TEMPLATE', $_SERVER['DOCUMENT_ROOT'] . '/incs/template/');
    define('CSS', $_SERVER['DOCUMENT_ROOT'] . '/css/');
    define('IMAGES', $_SERVER['DOCUMENT_ROOT'] . '/images/');
}


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.