it-swarm-ja.tech

完全なURLを PHP

完全なURLを取得するには、このコードを使用します。

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

問題は、私の.htaccessでいくつかのマスクを使用しているため、URLに表示されるものがファイルの実際のパスとは限らないことです。

必要なのは、URL、そのURLに書かれているもの、それ以上でもそれ以下でも - 完全なURLを取得することです。

サーバ上のファイルの実際のパスではなく、Webブラウザのナビゲーションバーに表示される方法を取得する必要があります。

978
DiegoP.

$_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を任意の値に設定できます。

1815
ax.

ウェブページ上のリンクを出力するためのショートバージョン

$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/形式 の問題とEdgeのケースについての詳細がここにあります。

完全版

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の大幅に変更されたバージョンです。

URLの構造

scheme:// username:password @ domain:port/path?query_string# fragment_id

太字の部分は関数に含まれません

ノート:

  • この関数は、完全なURLからのusername:passwordやフラグメント(ハッシュ)を含みません。
  • HTTPのデフォルトポート80およびHTTPSのポート443は表示されません。
  • Httpおよびhttpsスキームでのみテストされています。
  • #fragment_idは、クライアント(ブラウザ)によってサーバーに送信されず、完全なURLに追加されません。
  • $_GETは、foo=bar2のようなURLに対しては/example?foo=bar1&foo=bar2のみを含みます。
  • CMSや環境によっては$_SERVER['REQUEST_URI']を書き換えて/example?foo=bar2のようなURLに/example?foo=bar1&foo=bar2を返すでしょう。この場合は$_SERVER['QUERY_STRING']を使用してください。
  • _ uri _ = URL + URNであることを忘れないでください、しかし一般的な使用のために、URLは現在URIとURLの両方を意味します。
  • プロキシやバランサを使用する予定がない場合はHTTP_X_FORWARDED_Hostを削除する必要があります。
  • spec は、デフォルトの番号でない限り、Hostヘッダーにポート番号を含める必要があることを示しています。

クライアント(ブラウザ)制御変数:

  • $_SERVER['REQUEST_URI']。サポートされていない文字は送信される前にブラウザによってエンコードされます。
  • $_SERVER['HTTP_Host']そしてPHPマニュアルのコメントによると常に利用可能というわけではありません: http://php.net/manual/en/reserved.variables.php
  • $_SERVER['HTTP_X_FORWARDED_Host']はバランサによって設定され、PHPマニュアルの$_SERVER変数のリストには記載されていません。

サーバー制御変数

  • $_SERVER['HTTPS']。クライアントはこれを使用することを選択しますが、サーバーは空または "on"のいずれかの実際の値を返します。
  • $_SERVER['SERVER_PORT']。サーバーは許可された番号のみをポートとして受け入れます。
  • $_SERVER['SERVER_PROTOCOL']。サーバーは特定のプロトコルのみを受け入れます。
  • $_SERVER['SERVER_NAME']。これはサーバー設定で手動で設定され、 kralyk に従ってIPv6では使用できません。

関連する

HTTP_HostとSERVER_NAME
HTTPの「Host」ヘッダーパラメータにポート番号は必要ですか。
https://stackoverflow.com/a/28049503/175071

389
Timo Huovinen

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

// ======= PATHINFO ====== //
$x = pathinfo($url);
$x['dirname']      ???? https://example.com/subFolder
$x['basename']     ????                               myfile.php?
$x['extension']    ????                                      php?k=blaa#12345 // Unsecure! also, read my notice about hashtag parts    
$x['filename']     ????                               myfile

// ======= PARSE_URL ====== //
$x = parse_url($url);
$x['scheme']       ???? https
$x['Host']         ????         example.com
$x['path']         ????                    /subFolder/myfile.php
$x['query']        ????                                          k=blaa
$x['fragment']     ????                                                 12345 // ! read my notice about hashtag parts

//=================================================== //
//========== 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?k=blaa
$_SERVER["QUERY_STRING"]   ????                                             k=blaa
__FILE__                   ???? /home/user/public_html/subFolder/myfile.php
__DIR__                    ???? /home/user/public_html/subFolder              //same: dirname(__FILE__)
$_SERVER["REQUEST_URI"]    ????                       /subFolder/myfile.php?k=blaa
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?abc
__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(#...)URL部分はPHP(サーバー側)から検出できません。そのためには、JavaScriptを使用してください。
  • 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/  
206
T.Todua

これは 三項ステートメント を使った解決策で、コードを最小限に抑えます。

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

自分のWebサーバーが _ https _ に標準ポート443を使用していると仮定すると、これがこれを行うための最小かつ最も簡単な方法です。

56
honyovk

現在のURLを見つけるための私のお気に入りのクロスプラットフォームの方法は次のとおりです。

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

単に使用する:

$uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_Host'].$_SERVER['REQUEST_URI']
28
HappyCoder
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の情報を取得することはありません。このURLはわかりやすく、 "?hi = i&am = a&get"のようなものを削除します。

例:

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

次のように表示されます。

http://www.website.com/index

特定のコンテンツを定義するためにGetを使用しない限り、次に彼のコードを使用してください。 :-)

17

明確なコード、すべてのWebサーバー(Apache、nginx、IISなど)で機能します。

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

これが私の解決策です - コードは Tracy Debuggerに触発されています 。異なるサーバーポートをサポートするために変更されました。 $_SERVER['REQUEST_URI']を含む現在の完全なURL、または単に基本的なサーバー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/
10
OzzyCzech

私は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;
     }
 ?>
8

このワンライナーを使用して、親フォルダーのURLを見つけます(pecl_httpに付随するhttp_build_url()にアクセスできない場合)。

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

一般的な回答と同じ手法ですが、 _ https _ supportを使用し、読みやすくします。

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

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'];
6
Kai Noack

これはあなたのApache環境変数を使ってするのはとても簡単です。これはApache 2でしか動作しません。あなたが使っていると思います。

次のPHPコードを使うだけです。

<?php
    $request_url = Apache_getenv("HTTP_Host") . Apache_getenv("REQUEST_URI");
    echo $request_url;
?>
5
Amarjit

私の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

5

これを試して:

print_r($_SERVER);

$_SERVERは、ヘッダー、パス、スクリプトの場所などの情報を含む配列です。この配列のエントリはWebサーバーによって作成されます。すべてのWebサーバーがこれらのいずれかを提供するという保証はありません。サーバはいくつかを省略するか、またはここに記載されていない他のものを提供するかもしれません。とはいえ、»CGI/1.1仕様ではこれらの変数の多くが占められているので、それらを期待できるはずです。

$HTTP_SERVER_VARSは同じ初期情報を含みますが、スーパーグローバルではありません。 ($HTTP_SERVER_VARS$_SERVERは異なる変数であり、PHPはそれらをそのように扱います。)

5
php developer

現在のページの完全な _ url _ を取得するには、 http_build_url を引数なしで使用します。

$url = http_build_url();
5
Luke Mlsna

これはあなたの問題に対する解決策です:

//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;
4
Vaibhav Jain

私はこの文を使いました。

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

これがお役に立てば幸いです。

3
PhonPanom

私は以下のコードを使用しました、そしてそれは私のためにうまく動いています、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();

デモ

これは、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;

いくつかの異なる filters を使用して、好みに合わせて調整できます。

2
Coder
public static function getCurrentURL()
{
    $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']), 'https') === false ? 'http' : 'https';
    $Host = $_SERVER['HTTP_Host'];
    $script = $_SERVER['SCRIPT_NAME'];
    $params = $_SERVER['QUERY_STRING'] == '' ? '' : '?' . $_SERVER['QUERY_STRING'];

    return $protocol . '://' . $Host . $script . $params;
}
1
Mr.Hosseini

非常に簡単な使い方

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;
}
1
Abbas Arif
$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

1
hpaknia

以下のスニペットに示すように、HTTP_Originを使用できます。

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

これはHTTPとHTTPSの両方で機能します。

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

このようなものを出力してください。

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

0
Madan Sapkota

私はこの方法が良いと思います。

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/');
}
0
UWU_SANDUN