How to get base URL with PHP?

2019-01-02 19:46发布

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.

标签: php
19条回答
何处买醉
2楼-- · 2019-01-02 20:21

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();
?>
查看更多
旧时光的记忆
3楼-- · 2019-01-02 20:21
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;

}
查看更多
零度萤火
4楼-- · 2019-01-02 20:22

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 HTTP_HOST key (which contains user input), you still have to make some cleanup, remove spaces, commas, carriage return , anything that is not a valid character for a domain. Check php builtin parse_url functions for example.

查看更多
萌妹纸的霸气范
5楼-- · 2019-01-02 20:22

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!

查看更多
流年柔荑漫光年
6楼-- · 2019-01-02 20: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/"
//      }
查看更多
时光乱了年华
7楼-- · 2019-01-02 20:23

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.)

查看更多
登录 后发表回答