Как найти full url

Have a look at $_SERVER['REQUEST_URI'], i.e.

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

(Note that the double quoted string syntax is perfectly correct.)

If you want to support both HTTP and HTTPS, you can use

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

⚠️ Using this code has security implications because the client can set HTTP_HOST and REQUEST_URI to arbitrary values. It is absolutely necessary to sanitize both values and do meaningful input validation.

answered Jul 20, 2011 at 21:33

ax.'s user avatar

ax.ax.

58.1k8 gold badges80 silver badges72 bronze badges

59

Short version to output link on a webpage

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

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

Here are some more details about the issues and edge cases of the //example.com/path/ format

Full version

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;

This is a heavily modified version of http://snipplr.com/view.php?codeview&id=2734 (Which no longer exists)

URL structure:

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

The parts in bold will not be included by the function

Notes:

  • This function does not include username:password from a full URL or the fragment (hash).
  • It will not show the default port 80 for HTTP and port 443 for HTTPS.
  • Only tested with http and https schemes.
  • The #fragment_id is not sent to the server by the client (browser) and will not be added to the full URL.
  • $_GET will only contain foo=bar2 for an URL like /example?foo=bar1&foo=bar2.
  • Some CMS’s and environments will rewrite $_SERVER['REQUEST_URI'] and return /example?foo=bar2 for an URL like /example?foo=bar1&foo=bar2, use $_SERVER['QUERY_STRING'] in this case.
  • Keep in mind that an URI = URL + URN, but due to popular use, URL now means both URI and URL.
  • You should remove HTTP_X_FORWARDED_HOST if you do not plan to use proxies or balancers.
  • The spec says that the Host header must contain the port number unless it is the default number.

Client (Browser) controlled variables:

  • $_SERVER['REQUEST_URI']. Any unsupported characters are encoded by the browser before they are sent.
  • $_SERVER['HTTP_HOST'] and is not always available according to comments in the PHP manual: http://php.net/manual/en/reserved.variables.php
  • $_SERVER['HTTP_X_FORWARDED_HOST'] gets set by balancers and is not mentioned in the list of $_SERVER variables in the PHP manual.

Server controlled variables:

  • $_SERVER['HTTPS']. The client chooses to use this, but the server returns the actual value of either empty or “on”.
  • $_SERVER['SERVER_PORT']. The server only accepts allowed numbers as ports.
  • $_SERVER['SERVER_PROTOCOL']. The server only accepts certain protocols.
  • $_SERVER['SERVER_NAME'] . It is set manually in the server configuration and is not available for IPv6 according to kralyk.

Related:

What is the difference between HTTP_HOST and SERVER_NAME in PHP?
Is Port Number Required in HTTP “Host” Header Parameter?
https://stackoverflow.com/a/28049503/175071

answered Jan 17, 2012 at 8:57

Timo Huovinen's user avatar

Timo HuovinenTimo Huovinen

52.8k33 gold badges150 silver badges142 bronze badges

27

Examples for: 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["SERVER_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 the 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__;

Notice!

  • The hashtag # parts were manually used in the above example just for illustration purposes, however, server-side languages (including PHP) can’t natively detect them (only JavaScript can do that, as the hashtag is only browser/client side functionality).
  • DIRECTORY_SEPARATOR returns for Windows-type hosting, instead of /.

____

For 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/

Peter Mortensen's user avatar

answered Nov 15, 2014 at 9:59

T.Todua's user avatar

T.ToduaT.Todua

52.3k19 gold badges231 silver badges234 bronze badges

5

Here’s a solution using a ternary statement, keeping the code minimal:

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

This is the smallest and easiest way to do this, assuming one’s web server is using the standard port 443 for HTTPS.

Blackbam's user avatar

Blackbam

17.1k24 gold badges97 silver badges150 bronze badges

answered Apr 24, 2012 at 13:30

honyovk's user avatar

honyovkhonyovk

2,71718 silver badges26 bronze badges

3

My favorite cross platform method for finding the current URL is:

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

Yukulélé's user avatar

Yukulélé

15.3k10 gold badges67 silver badges93 bronze badges

answered May 18, 2014 at 1:54

Daniel Gillespie's user avatar

1

Simply use:

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

Peter Mortensen's user avatar

answered Dec 9, 2015 at 9:07

HappyCoder's user avatar

HappyCoderHappyCoder

5,9556 gold badges41 silver badges73 bronze badges

5

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;
}

Note: I just made an update to Timo Huovinen’s code, so you won’t get any GET parameters in the URL. This URL is plain and removes things like ?hi=i&am=a&get.

Example:

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

will be shown as:

http://www.example.com/index

This is fine unless you use GET paramaters to define some specific content, in which case you should use his code! 🙂

TRiG's user avatar

TRiG

10.1k7 gold badges57 silver badges107 bronze badges

answered Oct 26, 2012 at 13:15

Alex Westergaard's user avatar

2

Clear code, working in all webservers (Apache, nginx, IIS, …):

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

answered Apr 27, 2016 at 15:57

Andreas's user avatar

AndreasAndreas

2,79124 silver badges30 bronze badges

Same technique as the accepted answer, but with HTTPS support, and more readable:

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

The above gives unwanted slashes. On my setup Request_URI has leading and trailing slashes. This works better for me.

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

Rohit Gupta's user avatar

Rohit Gupta

4,01219 gold badges31 silver badges41 bronze badges

answered Nov 1, 2014 at 21:14

Jonathon Hill's user avatar

Jonathon HillJonathon Hill

3,4361 gold badge33 silver badges31 bronze badges

2

HTTP_HOST and REQUEST_URI must be in quotes, otherwise it throws an error in PHP 7.2

Use:

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

If you want to support both HTTP and HTTPS:

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

⚠️ Using this code has security implications because the client can set HTTP_HOST and REQUEST_URI to arbitrary values. It is absolutely necessary to sanitize both values and do input validation.

Having said this, it is best to determine the link server side without relying on the URL of the browser.

answered Jun 28, 2018 at 6:04

Avatar's user avatar

AvatarAvatar

14.3k9 gold badges118 silver badges194 bronze badges

Here is my solution – code is inspired by Tracy Debugger. It was changed for supporting different server ports. You can get full current URL including $_SERVER['REQUEST_URI'] or just the basic server URL. Check my function:

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);
    }
}

Here is test code:

// 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/

Peter Mortensen's user avatar

answered Aug 7, 2013 at 10:41

OzzyCzech's user avatar

OzzyCzechOzzyCzech

9,5463 gold badges49 silver badges33 bronze badges

1

I’ve made this function to handle the 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;
     }
 ?>

Peter Mortensen's user avatar

answered May 21, 2014 at 8:06

Web-Developer-Nil's user avatar

This is quite easy to do with your Apache environment variables. This only works with Apache 2, which I assume you are using.

Simply use the following PHP code:

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

Peter Mortensen's user avatar

answered Jul 20, 2011 at 21:52

Amarjit's user avatar

AmarjitAmarjit

3112 silver badges10 bronze badges

1

This is the solution for your problem:

//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;

Peter Mortensen's user avatar

answered Sep 26, 2013 at 6:33

Vaibhav Jain's user avatar

Vaibhav JainVaibhav Jain

4932 gold badges7 silver badges13 bronze badges

Try this:

print_r($_SERVER);

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)

Ram Sharma's user avatar

Ram Sharma

8,6567 gold badges43 silver badges56 bronze badges

answered Nov 6, 2013 at 7:52

php developer's user avatar

0

You can use http_build_url with no arguments to get the full URL of the current page:

$url = http_build_url();

Pang's user avatar

Pang

9,459146 gold badges81 silver badges122 bronze badges

answered Nov 24, 2014 at 4:56

Luke Mlsna's user avatar

Luke MlsnaLuke Mlsna

4584 silver badges16 bronze badges

1

Use this one-liner to find the parent folder URL (if you have no access to http_build_url() that comes along with pecl_http):

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

Peter Mortensen's user avatar

answered Feb 14, 2015 at 4:50

Ralph Rezende Larsen's user avatar

1

Here is the basis of a more secure version of the accepted answer, using PHP’s filter_input function, which also makes up for the potential lack of $_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;

You could use some different filters to tweak it to your liking.

answered Jun 18, 2018 at 19:06

Coder's user avatar

CoderCoder

2,7442 gold badges21 silver badges24 bronze badges

    public static function getCurrentUrl($withQuery = true)
    {
        $protocol = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
        or (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
        or (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
        or (isset($_SERVER['SERVER_PORT']) && intval($_SERVER['SERVER_PORT']) === 443) ? 'https' : 'http';

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

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

answered Jul 15, 2018 at 9:46

smarteist's user avatar

smarteistsmarteist

1,30112 silver badges15 bronze badges

1

I have used the below code, and it is working fine for me, for both cases, HTTP and 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();

Demo

Peter Mortensen's user avatar

answered Jan 22, 2017 at 5:48

thecodedeveloper.com's user avatar

2

I used this statement.

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

Peter Mortensen's user avatar

answered Mar 14, 2015 at 13:41

PhonPanom's user avatar

PhonPanomPhonPanom

3855 silver badges8 bronze badges

Very simple use:

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;
}

answered May 12, 2018 at 17:22

Abbas Arif's user avatar

Abbas ArifAbbas Arif

3624 silver badges16 bronze badges

3

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. 

Source: PHP Document Root, Path and URL detection

Peter Mortensen's user avatar

answered Jan 12, 2015 at 10:36

hpaknia's user avatar

hpakniahpaknia

2,7494 gold badges34 silver badges63 bronze badges

1

You can make use of HTTP_ORIGIN as illustrated in the snippet below:

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

nyedidikeke's user avatar

nyedidikeke

6,7517 gold badges43 silver badges57 bronze badges

answered Apr 13, 2017 at 8:35

ninja's user avatar

ninjaninja

4631 gold badge7 silver badges13 bronze badges

2

I think this method is good..try it

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

answered Jun 2, 2015 at 3:00

UWU_SANDUN's user avatar

UWU_SANDUNUWU_SANDUN

1,11313 silver badges19 bronze badges

In 2021

The above answers are working fine but not preferred by the Documentation because url.parse is now legacy so I suggest you to use new URL() function if you want to get more control on url.

Express Way

You can get Full URL from the below code.

`${req.protocol}://${req.get('host')}${req.originalUrl}`

Example URL: http://localhost:5000/a/b/c?d=true&e=true#f=false

Fixed Properties ( you will get the same results in all routes )

req.protocol: http
req.hostname: localhost
req.get('Host'): localhost:5000
req.originalUrl: /a/b/c?d=true&e=true
req.query: { d: 'true', e: 'true' }

Not Fixed Properties ( will change in every route because it controlled by express itself )

Route: /

req.baseUrl: <blank>
req.url: /a/b/c?d=true&e=true
req.path: /a/b/c

Route /a

req.baseUrl: /a
req.url: /b/c?d=true&e=true
req.path: /b/c

Documentation: http://expressjs.com/en/api.html#req.baseUrl

URL Package Way

In the URL function, you will get the same results in every route so properties are always fixed.

Properties

enter image description here

const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
console.log(url)

You will get the results like the below. I changed the order of the properties as per the image so it can match the image flow.

URL {
  href: 'http://localhost:5000/a/b/c?d=true&e=true',
  protocol: 'http:',
  username: '',
  password: '',
  hostname: 'localhost',
  port: '5000',
  host: 'localhost:5000',
  origin: 'http://localhost:5000',
  pathname: '/a/b/c',
  search: '?d=true&e=true',
  searchParams: URLSearchParams { 'd' => 'true', 'e' => 'true' },
  hash: ''
}

Note: Hash can not send to the server because it treats as Fragment in the server but you will get that in the client-side means browser.

Documentation: https://nodejs.org/api/url.html#url_new_url_input_base

Я использую этот код для получения полного URL:

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

Проблема в том, что я использую определенные маски в .htaccess. Поэтому то, что находится в URL-адресе, не всегда является реальным путем к файлу.

Мне нужно узнать его таким же, как он отображается на панели навигации в веб-браузере, а не реальный путь к файлу на сервере.

Ответ 1

Посмотрите $_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 на любое произвольное значение.

Ответ 2

Краткая версия для вывода ссылки на веб-страницу:

$url =  “//{$_SERVER[‘HTTP_HOST’]}{$_SERVER[‘REQUEST_URI’]}”;

$escaped_url = htmlspecialchars( $url, ENT_QUOTES, ‘UTF-8’ );

echo ‘<a href=”‘.$escaped_url.'”>’.$escaped_url.'</a>’;

Полная версия:

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;

Структура URL:

схема: // имя пользователя: пароль @ домен: порт / путь? query_string # fragment_id

Части, выделенные жирным шрифтом, не будут включены в функцию.

Заметки:

  • Эта функция не включает username:password полный URL или фрагмент (хэш).

  • Она не будет показывать порт 80 по умолчанию для HTTP и порт 443 для HTTPS.

  • Проверено только со схемами 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, если не планируете использовать прокси или балансировщики.

  • В спецификации сказано, что Host заголовок должен содержать номер порта, если он не является портом по умолчанию.

Переменные, контролируемые клиентом (браузером):

  • $_SERVER[‘REQUEST_URI’]. Любые неподдерживаемые символы кодируются браузером перед отправкой.

  • $_SERVER[‘HTTP_HOST’] не всегда доступен, согласно комментариям в руководстве по PHP.

  • $_SERVER[‘HTTP_X_FORWARDED_HOST’] устанавливается балансировщиками и не упоминается в списке $_SERVER переменных в руководстве по PHP.

Переменные, контролируемые сервером:

  • $_SERVER[‘HTTPS’]. Клиент выбирает использовать это, но сервер возвращает фактическое значение либо пусто, либо «включено».

  • $_SERVER[‘SERVER_PORT’]. Сервер принимает только разрешенные номера в качестве портов.

  • $_SERVER[‘SERVER_PROTOCOL’]. Сервер принимает только определенные протоколы.

  • $_SERVER[‘SERVER_NAME’]. Это задается вручную в конфигурации сервера и недоступно для IPv6.

Ответ 3

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;

}

URL stands for Uniform Resource Locator. It is used to locate some resources on the internet it can be thought of as a web address. The string you type on your browser search bar to get something from the internet is a URL, so in this process, the browser somehow finds the address of the server associated with that web address and says hey, this is the content(an URL) I have got from the user and now tell me how I should respond. Now it is the server’s responsibility to respond according to that request. And after receiving a response, it’s the browser’s responsibility to provide that received data to a user in the way it is expected.

Problem statement: So that was pretty much about URL, now our problem statement is how to get that URL at the server? Because during the application in production, several times we need the Whole components of URL to understand the user requirements so that later server can fulfill them by sending a proper response.  

Approach: There is an easy and simple approach to solve this because directly or indirectly the user sends the request object and it contains sufficient information for the server. And we can extract essential properties from that object according to our needs. In this article, at step number 4, we are going to discuss how to construct the URL from this request object sent by the user.

Step 1: Creating nodejs project and installing packages.

1. Create a nodejs application. As the whole operation is going to proceed with express framework hence it is the first compulsory step to create a node application.

npm init

2. This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package.json file, you can use `npm init -y` for default initialization.

Install express framework

npm install express

3. Create a new file app.js, inside this file, we will write the whole express code. 

Project Structure: It will look like the following.

Step 2: Creating an express application. So inside app.js do the following:

  1. Import express with require keyword and,
  2. Then call the express() function provided by the express framework.
  3. That function call will return our created app, store it in a const variable.
  4. Set a PORT for your application 3000 is default but you can choose any other according to availability.
  5. After then, call the listen() function, and with this our express server starts listening to the connection on the specified path.
  6. The listen function takes port and callback function as an argument.

The callback function provided as an argument gets executed either on the successful start of the server or it provides an error due to failure.

app.js

const express = require('express');

const app = express();             

const PORT = 3000;                 

app.listen(PORT, (error) => {      

    if(!error)

        console.log("Server is Successfully Running,

            and App is listening on port "+ PORT)

    else

        console.log("Error occurred, server can't start", error);

    }

);

Step 3: Now run the server with the provided command to check whether everything is working fine or not.

node app.js

If yes, then you’ll receive something like this in your terminal, otherwise, In case your server is not starting, analyze the error and check syntax, etc and then restart the server.

Step 4: So now we will continue to create routes and finding the full URL of the request, But let’s first understand the parts of a URL. Below is the description and image which shows the structure of an URL. 

  1. scheme: It is the protocol used to access the resource from the web, it may be HTTP or HTTPS, where ‘s’ stands for security, this scheme can be extracted by the .protocol property of request object like req.protocol.
  2. host: This is the name of the place where all the files required for the server exist in reality. The name of the host can be extracted from the .hostname property from request objects like req.hostname.
  3. port: It is the port number on which the server is listening, this port can be extracted directly in the server because we specify it before starts listening.
  4. path This path determines the actual location of the file, page, resource been accessed, actually, you can think of it as a sub-address it can be extracted by the concatenation of (req.baseUrl + req.path).
  5. query this query is used to provide some data before accessing the resources so that server can respond accordingly, it can be extracted by the req.query property of request objects.

Note: We don’t have to access the baseUrl, path, and query separately express provides us a property called req.originalUrl which contains everything after the hostname.   

The above example URL we are showing will be in your browser’s search bar when you click the algorithm section from the homepage of geeksforgeeks.org

Example: In this example, we are creating a route to receive user requests. We will use the following approach:

  1. In the route provided below, we have specified a function on the ‘*’ path for GET method.
  2. That’s because now we can send any URL from the browser to execute the given functionality.
  3. After then we are simply accessing some properties of the request object,  objectName.propertyName this is one of the ways to extract data.
  4. We have extracted 3 variables as protocol, hostname, and original URL.
  5. In the next line, we are storing the port number which we have set earlier.
  6. Later, We have created a URL string with template literals of ES6, the backticks are the way to create string templates and we can inject any javascript expression inside ${}.
  7. In the end, the function send()  is simply returning the string as a response.

app.js

app.get('*', function (req, res) {    

    const protocol = req.protocol;

    const host = req.hostname;

    const url = req.originalUrl;

    const port = process.env.PORT || PORT;

    const fullUrl = `${protocol}:

    const responseString = `Full URL is: ${fullUrl}`;                       

    res.send(responseString);  

})

Step to run the application: Open the terminal and type the following command.

node app.js

Output:

Explanation:  When we enter any Url in the browser search bar, the browser sends a request object to the server in our case the server is a localhost. And Express catches all user requests at the provided route and inside the functionality of that route. The scheme http extracted from req.protocol, and hostname localhost is extracted from req.hostname and 3000 is being accessed from the PORT which we have set before running the server in step 3, and the remaining URL is being extracted from req.originalUrl.

Last Updated :
18 Mar, 2023

Like Article

Save Article

Как в Яндекс.Браузере сделать так, чтобы показывался путь в адресной строке, как в Гугл Хром?

ПрограммыОтветы на вопросыЯндекс браузер

Niakita SR

28 июля 2021  · 3,4 K

Если вы хотите, чтобы Яндекс Браузер показывал полный URL-адрес страниц сайтов, то необходимо:

  1. Открыть раздел настроек «Интерфейс», подраздел «Умная строка» одним из 2 методов:
  • по ссылке browser://settings/interface?search=умная
  • меню → «Настройки» → «Интерфейс» → «Умная строка»
  1. Убрать отметку с пункта «Отображать адрес страниц в виде «домен > заголовок»» 

3,6 K

Эта настройка сделала возможным использовать этот браузер. Спасибо.

Комментировать ответ…Комментировать…

Если вас интересует полный URL страницы, то в Яндекс Браузере достаточно нажать на адресную строку мышкой (не на сам адрес, а на надпись рядом с ним) и увидите тоже самое, что и в Гугл. На скриншоте показала пример. Читать далее

2,8 K

Комментировать ответ…Комментировать…

Добавить комментарий