Get the full URL in PHP
Get the full URL in PHP
I use this code to get the full URL:
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
The problem is that I use some masks in my .htaccess
, so what we see in the URL is not always the real path of the file.
.htaccess
What I need is to get the URL, what is written in the URL, nothing more and nothing less—the full URL.
I need to get how it appears in the Navigation Bar in the web browser, and not the real path of the file on the server.
@eis Believe me, there's plenty of reasons to want this. Landing pages that use the same template but need to be tracked separately, etc. And the fact is that PHP (or any server side lang) can return all the various parts of the URL, but never seem to provide the whole thing in one string. It just seems dumb.
– Brade
Oct 29 '13 at 19:14
Whole thing is never sent to server side as it shouldn't matter, which is the reason it's not readily available anywhere. I would regard any functionality relying on that broken. But, that's just my opinion.
– eis
Oct 29 '13 at 20:31
My example above for the need of a self URL: "filling FORM action URLs" may be wrong, as PHP_SELF (path only, sans domain etc.) should be enough for that. But it doesn't necessarily mean that all other needs for the canonical self URL are invalid. If they indeed are, it would be awesome to see a thorough explanation, why.
– Sz.
Dec 7 '13 at 12:58
One of the reasons why you should not hardcode your URL in config is when you have different platforms where your project will be installed on(dev, integration, production). Each one of them will have their specific URL, and you don't want to change your code according to which server your project is installed on.
– Guillaume Fache
Apr 27 '16 at 7:40
30 Answers
30
Have a look at $_SERVER['REQUEST_URI']
, i.e.
$_SERVER['REQUEST_URI']
$actual_link = "http://$_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 = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Editor's note: using this code has security implications. The client can set HTTP_HOST and REQUEST_URI to any arbitrary value it wants.
What if you're on a https link? What if HTTP_HOST is not available or has been tampered with by client side? This answer seems incomplete and unreliable.
– Manachi
Apr 5 '13 at 2:07
Not much you can do about it, this is the proper method for the question asked.
– Mfoo
Apr 27 '13 at 12:45
This answer is not entirely true - the schema may be https
– Nigel Angel
Oct 4 '13 at 15:19
You can just add the check of HTTPS:
'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}/{$_SERVER['REQUEST_URI']}"
– ivkremer
Feb 22 '14 at 21:33
'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}/{$_SERVER['REQUEST_URI']}"
If you're outputting the URL to a browser as a link, just leave the http: off. See: stackoverflow.com/questions/4978235
– GameCharmer
Feb 26 '14 at 12:34
$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
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
.
http://snipplr.com/view.php?codeview&id=2734
scheme://username:password@domain:port/path?query_string#fragment_id
The parts in bold will not be included by the function
username:password
#fragment_id
$_GET
foo=bar2
/example?foo=bar1&foo=bar2
$_SERVER['REQUEST_URI']
/example?foo=bar2
/example?foo=bar1&foo=bar2
$_SERVER['QUERY_STRING']
URL + URN
HTTP_X_FORWARDED_HOST
Host
$_SERVER['REQUEST_URI']
$_SERVER['HTTP_HOST']
$_SERVER['HTTP_X_FORWARDED_HOST']
$_SERVER
$_SERVER['HTTPS']
$_SERVER['SERVER_PORT']
$_SERVER['SERVER_PROTOCOL']
$_SERVER['SERVER_NAME']
HTTP_HOST vs. SERVER_NAME
Is Port Number Required in HTTP "Host" Header Parameter?
https://stackoverflow.com/a/28049503/175071
This code will fail if the server is given by IPv6 IP address. To fix that, replace SERVER_NAME with HTTP_HOST.
– kralyk
Nov 22 '12 at 17:05
note:
$_SERVER['REQUEST_URI']
will show /example?foo=bar2
for url like /example?foo=bar1&foo=bar2
– Timo Huovinen
May 9 '13 at 13:36
$_SERVER['REQUEST_URI']
/example?foo=bar2
/example?foo=bar1&foo=bar2
This would not contain anything defined after a #, those aren't passed through to the server
– William King
Jun 5 '13 at 18:57
I'm unsure if that is no security risk. In your example you can send the Host header to reach the correct page but might let the page think it is called via another host using the HTTP_X_FORWARDED_HOST header. When the application uses this information (for whatever) it can be indeed a security problem as it allows you to promise something what isn't the case.
– hek2mgl
Dec 6 '13 at 11:08
@Matt3o12 The value of the port is taken directly from the
Host
header, haven't seen it set like that, thanks for mentioning it, will add it as a tweak– Timo Huovinen
Apr 25 '14 at 20:19
Host
For that matter, just have a look at the whole array with print_r($_SERVER)
, you'll see everything you need there :)
print_r($_SERVER)
@ChenAsraf except you won't see everything in $_SERVER, for example any of the HTTP_X variables. See the comment here on how to get a bigger list from searching
phpinfo()
on dogpile– Timo Huovinen
Oct 18 '13 at 7:36
phpinfo()
Unfortunately, it is really not that simple to get the current URL. So this answer is not helpful.
– mermshaus
Oct 25 '15 at 16:40
Examples for URL: https://example.com/subFolder/yourfile.php?var=blabla#12345
https://example.com/subFolder/yourfile.php?var=blabla#12345
//built-in function
$x = parse_url($url);
$x['scheme'] 🡺 https
$x['host'] 🡺 example.com (or with WWW)
$x['path'] 🡺 /subFolder/yourfile.php
$x['query'] 🡺 var=blabla
$x['fragment'] 🡺 12345 // hashtag outputed only in case, when hashtag-containing string was manually passed to function, otherwise PHP is unable to recognise hashtags in $_SERVER
//built-in function (with this function, I only recommend to pass `parse_url`s output as argument)
$A = pathinfo($url);
$B = pathinfo(parse_url($url)['path']);
$A['dirname'] 🡺 https://example.com/subFolder
$B['dirname'] 🡺 /subFolder
$A['basename'] 🡺 yourfile.php?var=blabla#12345
$B['basename'] 🡺 yourfile.php
$A['extension'] 🡺 php?var=blabla#12345
$B['extension'] 🡺 php
$A['filename'] 🡺 yourfile
$B['filename'] 🡺 yourfile
//=================================================== //
//========== 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/yourfile.php?var=blabla
$_SERVER["QUERY_STRING"] 🡺 var=blabla
__FILE__ 🡺 /home/user/public_html/subFolder/yourfile.php
__DIR__ 🡺 /home/user/public_html/subFolder //same: dirname(__FILE__)
$_SERVER["REQUEST_URI"] 🡺 /subFolder/yourfile.php?var=blabla
parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)🡺 /subFolder/yourfile.php
$_SERVER["PHP_SELF"] 🡺 /subFolder/yourfile.php
// ==================================================================//
//if "YOURFILE.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/yourfile.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) 🡺 yourfile.php
//excellent solution to find origin
$debug_files = debug_backtrace(); $initial_called_file = count($debug_files) ? $debug_files[count($debug_files) - 1]['file'] : __FILE__;
Notice!:
DIRECTORY_SEPARATOR
/
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/
Where is the # part, Is there no way we can access part after # on the server side?
– Rohit Khatri
Aug 8 '16 at 7:01
unfortunately no, SERVER doesnt recognize that.. it is detectable in client-side Browser (i.e javascript)
– T.Todua
Aug 11 '16 at 6:30
Can you show it in Zend Framework?
– YumYumYum
Sep 29 '16 at 13:21
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.
Or use
$_SERVER["HTTPS"] == "on"
to check if SSL is on.– hasMobi - Android Apps
Aug 5 '13 at 9:08
$_SERVER["HTTPS"] == "on"
You should be using $_SERVER["HTTPS"] because port 443 is only the default SSL port, not an SSL indicator.
– Alex Barker
Sep 18 '13 at 22:22
@AlexBarker - That's why I said "assuming one's web server is using the standard Port 443 for HTTPS."
– honyovk
Sep 18 '13 at 22:59
My favorite cross platform method for finding the current URL is:
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Close, but I needed to change it to this: $url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
– Erik Allen
Feb 12 '16 at 16:46
Simply use:
$uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
As much as I want to use this, it doesn't work in IIS. stackoverflow.com/questions/18008135/…
– Erik Allen
Feb 12 '16 at 16:44
What does it output?
– HappyCoder
Feb 13 '16 at 17:08
PHP Notice: Undefined index: REQUEST_SCHEME
– Erik Allen
Feb 16 '16 at 16:24
i love this solution ! but can you also make it work for nginx ?
– cowboysaif
Feb 29 '16 at 16:29
http://example.com
:8080
/request.php
and fail. These answers are complicated for a reason.– DRS David Soft
Sep 29 '16 at 16:14
http://example.com
:8080
/request.php
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's into the URL. This URL is plain and removes things like " ?hi=i&am=a&get ".
Example:
http://www.website.com/index?get=information
will be shown as:
http://www.website.com/index
Unless you use Get's to define some specific content, then use his code! :-)
hey thats, pretty cool :) you could also remove anything after a hash "#" (url fragment) in case it somehow slips in
– Timo Huovinen
Nov 22 '12 at 18:37
Not really, because if you set in " explode('#',$segment[0]) ", it will count as error, because " # " the symbol breaks the URL, and can only be read by Javascript. But what you can do, to be sure, is that you can remake the " return $url; " with " return trim($url,'#'); ", because then you will remove it, in case it will be there. But it will not remove the following content. You can read up on "Parse_url" if you want to. :-)
– Alex Westergaard
Nov 28 '12 at 17:27
Clear code, working in all webservers (Apache, nginx, IIS, ...):
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Here is my solution - code is inspired by Tracy Debugger. It was changed for support different server ports. You can get full current URL including $_SERVER['REQUEST_URI']
or just the basic server URL. Check my function:
$_SERVER['REQUEST_URI']
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/
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;
}
?>
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']
);
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__)));
you mix url and file absolute location on disk
– sd1sd1
Oct 1 '15 at 8:49
I've made this class to handle my URI's
<?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();
}
Of course you have to adapt it to your needs and system !?!
<?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.
');
It still needs to be perfected but it's a god solution for a centralized URI system :D
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;
?>
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;
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.
$_SERVER
$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)
$HTTP_SERVER_VARS
$HTTP_SERVER_VARS
$_SERVER
You can use http_build_url with no arguments to get the full URL of the current page:
$url = http_build_url();
Note that http_build_url() is a PECL function only: (PECL pecl_http >= 0.21.0)
– Volomike
Jul 10 '15 at 22:59
I used this statement.
$base = "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]$my_web_base_path";
$url = $base . "/" . dirname(dirname(__FILE__));
I hope this will help you.
Try this:
$pageURL = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
$pageURL .= $_SERVER['SERVER_PORT'] != '80' ? $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"] : $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
echo $pageURL;
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
interchange position of http and https.
– Shwet
Feb 8 '17 at 5:29
Unless I'm mistaken,
$_SERVER['HTTPS'] = 'off'
will trigger the HTTPS path. That doesn't seem right. On the other hand, I don't think the original logic was right either.– Nisse Engström
Feb 8 '17 at 21:00
$_SERVER['HTTPS'] = 'off'
$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:
http://blog.lavoie.sl/2013/02/php-document-root-path-and-url-detection.html
You can make use of HTTP_ORIGIN
as illustrated in the snippet below:
HTTP_ORIGIN
if ( ! array_key_exists( 'HTTP_ORIGIN', $_SERVER ) ) {
$this->referer = $_SERVER['SERVER_NAME'];
} else {
$this->referer = $_SERVER['HTTP_ORIGIN'];
}
$url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
Above line store full URL in the variable $url. It includes https/http, subdomain, domain requested page.
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;
}
Hi, given how many answers there already are on this page, could you add a bit of explanation about why this is better than the others, or what it does differently?
– IMSoP
May 12 at 17:25
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/');
}
This works for both HTTP and HTTPS.
echo 'http' . (($_SERVER['HTTPS'] == 'on') ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Output something like this.
https://example.com/user.php?token=3f0d9sickc0flmg8hnsngk5u07&access_level=application
$page_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
For more: https://codeupweb.wordpress.com/2017/10/11/how-to-get-the-full-url-of-page-using-php/
This answer has been copied from above.
– DanFromGermany
Feb 2 at 10:28
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']
:
$_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.
Since my edit of the best answer was rolled back, I am posting this as a separate answer:
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'];
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
@Brade URL bar is on the user browser, so why would PHP have any functionalities regarding that? PHP is server side.
– eis
Oct 19 '13 at 11:53