160

I am using XAMPP on Windows Vista. In my development, I have http://127.0.0.1/test_website/.

How do I get http://127.0.0.1/test_website/ with PHP?

I tried something like these, but none of them worked.

echo dirname(__FILE__)
or
echo basename(__FILE__);
etc.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
shin
  • 31,901
  • 69
  • 184
  • 271

25 Answers25

284

Try this:

<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>

Learn more about the $_SERVER predefined variable.

If you plan on using https, you can use this:

function url(){
  return sprintf(
    "%s://%s%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}

echo url();
#=> http://127.0.0.1/foo

Per this answer, please make sure to configure your Apache properly so you can safely depend on SERVER_NAME.

<VirtualHost *>
    ServerName example.com
    UseCanonicalName on
</VirtualHost>

NOTE: If you're depending on the HTTP_HOST key (which contains user input), you still have to make some cleanup, remove spaces, commas, carriage return, etc. Anything that is not a valid character for a domain. Check the PHP builtin parse_url function for an example.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
maček
  • 76,434
  • 37
  • 167
  • 198
  • 2
    Should check `$_SERVER['HTTPS']` and swap in `https://` instead of `http://` in those cases. – ceejayoz May 12 '10 at 16:26
  • Be careful, in protocol you must add "://" – Brice Favre Jun 09 '10 at 12:55
  • If you are running PHP on Windows with IIS, then the S_SERVER['HTTPS'] variable returns the value _off_ when not using _https_. So for IIS I changed the first line of the function to the following: $protocol = $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off' ? "https" : "http"; – BruceHill Jun 05 '12 at 12:46
  • @maček You should use isset for `$protocol = ($_SERVER['HTTPS'])` else some servers will throw undefined index error so `$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off")` – Mr. Alien Apr 10 '13 at 05:56
  • I like the solution posted by [Double Gras](http://stackoverflow.com/users/289317/double-gras) found here: http://stackoverflow.com/questions/1175096/how-to-find-out-if-you-are-using-https-without-serverhttps seems – Kyle Coots May 24 '13 at 00:42
  • I agree with @Mr.Alien you should check if $_SERVER['HTTPS'] is set because it will yield a "Notice: Undefined index: HTTPS in..." error. Should be: `function url(){ $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http"; return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; }` – lucentx Jul 16 '13 at 01:28
  • @lucentx, I refreshed this answer to address your comment. Sadly this can't be made much nicer. – maček Jul 16 '13 at 07:25
  • 2
    what about $_SERVER['REQUEST_SCHEME']? isn't that simpler? – frostymarvelous Apr 02 '14 at 17:52
  • @frostymarvelous, I don't see `REQUEST_SCHEME` documented in the [$_SERVER docs](http://www.php.net/manual/en/reserved.variables.server.php). If I try to echo it, I just get `Notice: Undefined index: REQUEST_SCHEME`. Maybe you have a script/framework that is setting this value for you? – maček Apr 02 '14 at 18:00
  • I guess it might be Apache then. I have this on both my AWS server and local servers both running Apache. Thanks @maček – frostymarvelous Apr 02 '14 at 18:09
  • Thank you , it even helped in my drupal php function – Hitesh Aug 21 '14 at 12:21
  • 3
    This does not work if you are using a port different from 80. :( – M'sieur Toph' Feb 10 '15 at 09:48
  • Reverted [Swarnendu's edit](http://stackoverflow.com/revisions/2820771/10), as `$_SERVER['REQUEST_URI']` includes a starting `/`. – admdrew Aug 18 '15 at 20:20
  • 1
    @admdrew thanks. I double-checked that `REQUEST_URI` already includes a `/`; it does. [@swarnendu](http://stackoverflow.com/users/1531473/swarnendu-paul) please be more careful when editing other people's answers. That should've been a comment instead. – maček Aug 19 '15 at 04:59
  • using `SERVER_NAME` doesn't include dynamic sub domains. you're better using `HTTP_HOST` instead. – N69S Sep 16 '19 at 10:58
32

Function adjusted to execute without warnings:

function url(){
    if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }
    else{
        $protocol = 'http';
    }
    return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ftrotter
  • 3,066
  • 2
  • 38
  • 52
23

Fun 'base_url' snippet!

if (!function_exists('base_url')) {
    function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
        if (isset($_SERVER['HTTP_HOST'])) {
            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
            $hostname = $_SERVER['HTTP_HOST'];
            $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
            $core = $core[0];

            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
            $base_url = sprintf( $tmplt, $http, $hostname, $end );
        }
        else $base_url = 'http://localhost/';

        if ($parse) {
            $base_url = parse_url($base_url);
            if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
        }

        return $base_url;
    }
}

Use as simple as:

//  url like: http://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php

echo base_url();    //  will produce something like: http://stackoverflow.com/questions/2820723/
echo base_url(TRUE);    //  will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE);    //  will produce something like: http://stackoverflow.com/questions/
//  and finally
echo base_url(NULL, NULL, TRUE);
//  will produce something like: 
//      array(3) {
//          ["scheme"]=>
//          string(4) "http"
//          ["host"]=>
//          string(12) "stackoverflow.com"
//          ["path"]=>
//          string(35) "/questions/2820723/"
//      }
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
17
   $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';

Usage:

print "<script src='{$base_url}js/jquery.min.js'/>";
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
user3832931
  • 677
  • 7
  • 6
15
$modifyUrl = parse_url($url);
print_r($modifyUrl)

Its just simple to use
Output :

Array
(
    [scheme] => http
    [host] => aaa.bbb.com
    [path] => /
)
agravat.in
  • 561
  • 6
  • 14
  • @AnjaniBarnwal can you explain why? I think this is the best way if you have a string with an url and want to get the base url like `https://example.com` from `https://example.com/category2/page2.html?q=2#lorem-ipsum` - that has nothing to do with the current page you are at. – OZZIE Feb 04 '19 at 14:45
7

I think the $_SERVER superglobal has the information you're looking for. It might be something like this:

echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']

You can see the relevant PHP documentation here.

Jeremy DeGroot
  • 4,496
  • 2
  • 20
  • 21
  • this keeps redirecting to same page user is at now. how can I fix this to redirect to home page? Im on apache, localhost. php7 – Joey Dec 14 '17 at 08:06
6

Try the following code :

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];

The first line is checking if your base url used http or https then the second line is use to get the hostname .Then the third line use to get only base folder of your site ex. /test_website/

rrsantos
  • 404
  • 4
  • 14
5

You can do it like this, but sorry my english is not good enough.

First, get home base url with this simple code..

I've tested this code on my local server and public and the result is good.

<?php

function home_base_url(){   

// first get http protocol if http or https

$base_url = (isset($_SERVER['HTTPS']) &&

$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';

// get default website root directory

$tmpURL = dirname(__FILE__);

// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",

//convert value to http url use string replace, 

// replace any backslashes to slash in this case use chr value "92"

$tmpURL = str_replace(chr(92),'/',$tmpURL);

// now replace any same string in $tmpURL value to null or ''

// and will return value like /localhost/my_website/ or just /my_website/

$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);

// delete any slash character in first and last of value

$tmpURL = ltrim($tmpURL,'/');

$tmpURL = rtrim($tmpURL, '/');


// check again if we find any slash string in value then we can assume its local machine

    if (strpos($tmpURL,'/')){

// explode that value and take only first value

       $tmpURL = explode('/',$tmpURL);

       $tmpURL = $tmpURL[0];

      }

// now last steps

// assign protocol in first value

   if ($tmpURL !== $_SERVER['HTTP_HOST'])

// if protocol its http then like this

      $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';

    else

// else if protocol is https

      $base_url .= $tmpURL.'/';

// give return value

return $base_url; 

}

?>

// and test it

echo home_base_url();

output will like this :

local machine : http://localhost/my_website/ or https://myhost/my_website 

public : http://www.my_website.com/ or https://www.my_website.com/

use home_base_url function at index.php of your website and define it

and then you can use this function to load scripts, css and content via url like

<?php

echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";

?>

will create output like this :

<script type="text/javascript" src="http://www.my_website.com/js/script.js"></script>

and if this script works fine,,!

Jared Forth
  • 1,577
  • 6
  • 17
  • 32
Crazy SagaXxX
  • 51
  • 1
  • 1
5

Simple and easy trick:

$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseurl = "http://" . $host . $path . "/";

URL looks like this: http://example.com/folder/

3rdthemagical
  • 5,271
  • 18
  • 36
Ali Akhtar
  • 51
  • 1
  • 1
5

The following code will reduce the problem to check the protocol. The $_SERVER['APP_URL'] will display the domain name with the protocol

$_SERVER['APP_URL'] will return protocol://domain ( eg:-http://localhost)

$_SERVER['REQUEST_URI'] for remaining parts of the url such as /directory/subdirectory/something/else

 $url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI'];

The output would be like this

http://localhost/directory/subdirectory/something/else

Jijesh Cherayi
  • 1,111
  • 12
  • 15
  • 1
    Rather than just pasting a random bunch of code, explain what you did and why. That way, the OP and any future readers with the same problem can actually learn something from your answer, rather than just copy/pasting it and asking the same question again tomorrow. – Oldskool May 13 '16 at 08:56
4

I found this on http://webcheatsheet.com/php/get_current_page_url.php

Add the following code to a page:

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

You can now get the current page URL using the line:

<?php
  echo curPageURL();
?>

Sometimes it is needed to get the page name only. The following example shows how to do it:

<?php
function curPageName() {
 return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}

echo "The current page name is ".curPageName();
?>
Hoàng Vũ Tgtt
  • 1,863
  • 24
  • 8
2
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";

$url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
Farid Bangash
  • 84
  • 1
  • 7
2

Try this. It works for me.

/*url.php file*/

trait URL {
    private $url = '';
    private $current_url = '';
    public $get = '';

    function __construct()
    {
        $this->url = $_SERVER['SERVER_NAME'];
        $this->current_url = $_SERVER['REQUEST_URI'];

        $clean_server = str_replace('', $this->url, $this->current_url);
        $clean_server = explode('/', $clean_server);

        $this->get = array('base_url' => "/".$clean_server[1]);
    }
}

Use like this:

<?php
/*
Test file

Tested for links:

http://localhost/index.php
http://localhost/
http://localhost/index.php/
http://localhost/url/index.php    
http://localhost/url/index.php/  
http://localhost/url/ab
http://localhost/url/ab/c
*/

require_once 'sys/url.php';

class Home
{
    use URL;
}

$h = new Home();

?>

<a href="<?=$h->get['base_url']?>">Base</a>
Ali
  • 1,358
  • 3
  • 21
  • 32
2

This is the best method i think so.

$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http");
$base_url .= "://".$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

echo $base_url;
Rajat Masih
  • 537
  • 1
  • 6
  • 19
2

The following solution will work even when the current url has request query string.

<?php 

function baseUrl($file=__FILE__){
    $currentFile = array_reverse(explode(DIRECTORY_SEPARATOR,$file))[0];
    if(!empty($_SERVER['QUERY_STRING'])){
        $currentFile.='?'.$_SERVER['QUERY_STRING'];
    }
    $protocol = $_SERVER['PROTOCOL'] == isset($_SERVER['HTTPS']) &&     
                              !empty($_SERVER['HTTPS']) ? 'https' : 'http';
    $url = "$protocol://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $url = str_replace($currentFile, '', $url);

    return $url;
}

The calling file will provide the __FILE__ as param

<?= baseUrl(__FILE__)?>
Bellash
  • 7,560
  • 6
  • 53
  • 86
1

Here's one I just put together that works for me. It will return an array with 2 elements. The first element is everything before the ? and the second is an array containing all of the query string variables in an associative array.

function disectURL()
{
    $arr = array();
    $a = explode('?',sprintf(
        "%s://%s%s",
        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
        $_SERVER['SERVER_NAME'],
        $_SERVER['REQUEST_URI']
    ));

    $arr['base_url']     = $a[0];
    $arr['query_string'] = [];

    if(sizeof($a) == 2)
    {
        $b = explode('&', $a[1]);
        $qs = array();

        foreach ($b as $c)
        {
            $d = explode('=', $c);
            $qs[$d[0]] = $d[1];
        }
        $arr['query_string'] = (count($qs)) ? $qs : '';
    }

    return $arr;

}

Note: This is an expansion of the answer provided by maček above. (Credit where credit is due.)

Kenny
  • 2,150
  • 2
  • 22
  • 30
1

Edited at @user3832931 's answer to include server port..

to form URLs like 'https://localhost:8000/folder/'

$base_url="http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER["REQUEST_URI"].'?').'/';
Badmus Taofeeq
  • 761
  • 9
  • 18
0
$some_variable =  substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1);

and you get something like

lalala/tralala/something/
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
  • There is much code on this Q&A entry that belongs into the danger zone, this one as well especially because of the use of PHP_SELF. – hakre Sep 24 '15 at 16:36
0

Try using: $_SERVER['SERVER_NAME'];

I used it to echo the base url of my site to link my css.

<link href="//<?php echo $_SERVER['SERVER_NAME']; ?>/assets/css/your-stylesheet.css" rel="stylesheet" type="text/css">

Hope this helps!

KAZZABE
  • 197
  • 2
  • 10
0

In my case I needed the base URL similar to the RewriteBasecontained in the .htaccess file.

Unfortunately simply retrieving the RewriteBase from the .htaccess file is impossible with PHP. But it is possible to set an environment variable in the .htaccess file and then retrieve that variable in PHP. Just check these bits of code out:

.htaccess

SetEnv BASE_PATH /

index.php

Now I use this in the base tag of the template (in the head section of the page):

<base href="<?php echo ! empty( getenv( 'BASE_PATH' ) ) ? getenv( 'BASE_PATH' ) : '/'; ?>"/>

So if the variable was not empty, we use it. Otherwise fallback to / as default base path.

Based on the environment the base url will always be correct. I use / as the base url on local and production websites. But /foldername/ for on the staging environment.

They all had their own .htaccess in the first place because the RewriteBase was different. So this solution works for me.

Floris
  • 2,727
  • 2
  • 27
  • 47
0

Currently this is the proper answer:

$baseUrl = $_SERVER['REQUEST_SCHEME'];
$baseUrl .= '://'.$_SERVER['HTTP_HOST'];

You might want to add a / to the end. Or you might want to add

$baseUrl .= $_SERVER['REQUEST_URI'];

so in total copy paste

$baseUrl = $_SERVER['REQUEST_SCHEME']
    . '://' . $_SERVER['HTTP_HOST']
    . $_SERVER['REQUEST_URI'];
theking2
  • 2,174
  • 1
  • 27
  • 36
-1
function server_url(){
    $server ="";

    if(isset($_SERVER['SERVER_NAME'])){
        $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], '/');
    }
    else{
        $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_ADDR'], '/');
    }
    print $server;

}
-1

I had the same question as the OP, but maybe a different requirement. I created this function...

/**
 * Get the base URL of the current page. For example, if the current page URL is
 * "https://example.com/dir/example.php?whatever" this function will return
 * "https://example.com/dir/" .
 *
 * @return string The base URL of the current page.
 */
function get_base_url() {

    $protocol = filter_input(INPUT_SERVER, 'HTTPS');
    if (empty($protocol)) {
        $protocol = "http";
    }

    $host = filter_input(INPUT_SERVER, 'HTTP_HOST');

    $request_uri_full = filter_input(INPUT_SERVER, 'REQUEST_URI');
    $last_slash_pos = strrpos($request_uri_full, "/");
    if ($last_slash_pos === FALSE) {
        $request_uri_sub = $request_uri_full;
    }
    else {
        $request_uri_sub = substr($request_uri_full, 0, $last_slash_pos + 1);
    }

    return $protocol . "://" . $host . $request_uri_sub;

}

...which, incidentally, I use to help create absolute URLs that should be used for redirecting.

ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253
-1

Just test and get the result.

// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
echo $protocol.$hostName.$pathInfo['dirname']."/";
Anjani Barnwal
  • 1,362
  • 1
  • 17
  • 23
-1
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";
$dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '',$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']);
echo $url = $http . $dir;
// echo $url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];