【问题标题】:How do I get the base URL with PHP?如何使用 PHP 获取基本 URL?
【发布时间】:2011-02-18 17:28:15
【问题描述】:

我在 Windows Vista 上使用 XAMPP。在我的开发中,我有http://127.0.0.1/test_website/

如何使用 PHP 获得 http://127.0.0.1/test_website/

我尝试了类似的方法,但都没有奏效。

echo dirname(__FILE__)
or
echo basename(__FILE__);
etc.

【问题讨论】:

  • 他们怎么不工作?他们返回了什么?
  • @animuson 这些常量返回本地文件系统路径,而不是 URL。
  • Get the full URL in PHP的可能重复

标签: php


【解决方案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'];

【讨论】:

  • 如果你能在你的代码中添加一点解释就好了。
【解决方案2】:

这是我认为最好的方法。

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

【讨论】:

    【解决方案3】:

    试试下面的代码:

    $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'];
    

    【讨论】:

    • 这个答案缺少教育解释。
    【解决方案4】:

    试试这个:

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

    详细了解$_SERVER predefined variable

    如果你打算使用 https,你可以使用这个:

    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
    

    根据this answer,请确保正确配置您的Apache,以便您可以安全地依赖SERVER_NAME

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

    注意:如果您依赖 HTTP_HOST 键(包含用户输入),您仍然需要进行一些清理,删除空格、逗号、回车等。不是域的有效字符。查看 PHP 内置的 parse_url 函数以获取示例。

    【讨论】:

    • 在这些情况下应该检查$_SERVER['HTTPS']并换成https://而不是http://
    • 谢谢你,我需要这个功能。
    • $_SERVER['REQUEST_SCHEME'] 怎么样?不是更简单吗?
    • 如果您使用的端口不是 80,这将不起作用。:(
    • @admdrew 谢谢。我仔细检查了REQUEST_URI 已经包含/;确实如此。 @swarnendu 编辑其他人的答案时请多加小心。那应该是评论。
    【解决方案5】:

    在我的例子中,我需要类似于 RewriteBase 包含在 .htaccess 文件中的基本 URL。

    不幸的是,简单地从.htaccess 文件中检索RewriteBase 是不可能使用PHP 的。 但可以在 .htaccess 文件中设置环境变量,然后在 PHP 中检索该变量。只需检查这些代码:

    .htaccess

    SetEnv BASE_PATH /
    

    index.php

    现在我在模板的基本标记中使用它(在页面的头部):

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

    所以如果变量不为空,我们就使用它。否则回退到 / 作为默认基本路径。

    根据环境,基本 url 总是正确的。我使用/ 作为本地和生产网站的基本网址。但是/foldername/ 用于暂存环境。

    首先他们都有自己的.htaccess,因为 RewriteBase 不同。所以这个解决方案对我有用。

    【讨论】:

      【解决方案6】:

      你可以这样做,但抱歉我的英语不够好。

      首先,用这个简单的代码获取家庭基地网址..

      我已经在本地服务器和公共服务器上测试了这段代码,结果很好。

      <?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();
      

      输出会是这样的:

      local machine : http://localhost/my_website/ or https://myhost/my_website 
      
      public : http://www.my_website.com/ or https://www.my_website.com/
      

      在您网站的index.php 处使用home_base_url 函数并定义它

      然后你可以使用这个函数通过url加载脚本、css和内容

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

      将创建这样的输出:

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

      如果这个脚本运行良好,,!

      【讨论】:

        【解决方案7】:

        只需测试并获得结果。

        // 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']."/";
        

        【讨论】:

          【解决方案8】:
          $some_variable =  substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1);
          

          然后你得到 像

          lalala/tralala/something/
          

          【讨论】:

          • 这个Q&A条目中有很多代码属于危险区域,特别是因为使用了PHP_SELF。
          【解决方案9】:
             $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';
          

          用法:

          print "<script src='{$base_url}js/jquery.min.js'/>";
          

          【讨论】:

            【解决方案10】:

            简单易行的技巧:

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

            网址如下所示:http://example.com/folder/

            【讨论】:

              【解决方案11】:

              我和 OP 有同样的问题,但可能有不同的要求。我创建了这个函数...

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

              ...顺便说一下,我用它来帮助创建应该用于重定向的绝对 URL。

              【讨论】:

                【解决方案12】:

                尝试使用:$_SERVER['SERVER_NAME'];

                我用它来回显我网站的基本 url 以链接我的 css。

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

                希望这会有所帮助!

                【讨论】:

                  【解决方案13】:

                  试试这个。它对我有用。

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

                  这样使用:

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

                  【讨论】:

                    【解决方案14】:

                    在@user3832931 的回答中编辑以包含服务器端口..

                    形成像'https://localhost:8000/folder/'这样的URL

                    $base_url="http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER["REQUEST_URI"].'?').'/';
                    

                    【讨论】:

                      【解决方案15】:
                      $modifyUrl = parse_url($url);
                      print_r($modifyUrl)
                      

                      简单易用
                      输出:

                      Array
                      (
                          [scheme] => http
                          [host] => aaa.bbb.com
                          [path] => /
                      )
                      

                      【讨论】:

                      • @AnjaniBarnwal 你能解释一下为什么吗?我认为如果您有一个带有 url 的字符串并且想要从 https://example.com/category2/page2.html?q=2#lorem-ipsum 获取像 https://example.com 这样的基本 url,这是最好的方法 - 这与您所在的当前页面无关。
                      【解决方案16】:

                      以下代码将减少检查协议的问题。 $_SERVER['APP_URL'] 将显示带有协议的域名

                      $_SERVER['APP_URL'] 将返回 protocol://domain(例如:-http://localhost

                      $_SERVER['REQUEST_URI'] 用于 url 的其余部分,例如 /directory/subdirectory/something/else

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

                      输出是这样的

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

                      【讨论】:

                      • 与其只是随意粘贴一堆代码,不如解释一下你做了什么以及为什么。这样,OP 和任何有相同问题的未来读者实际上都可以从您的答案中学到一些东西,而不是仅仅复制/粘贴它并在明天再次提出相同的问题。
                      【解决方案17】:

                      有趣的“base_url”sn-p!

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

                      使用简单如下:

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

                      【讨论】:

                        【解决方案18】:

                        这是我刚刚整理的对我有用的一个。它将返回一个包含 2 个元素的数组。第一个元素是 ? 之前的所有内容第二个是一个数组,其中包含关联数组中的所有查询字符串变量。

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

                        注意:这是上面 maček 提供的答案的扩展。 (信用到期的信用。)

                        【讨论】:

                          【解决方案19】:
                          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;
                          
                          }
                          

                          【讨论】:

                          • 冗余/WET 风格没有吸引力。这个只有代码的答案缺少教育解释。
                          【解决方案20】:

                          我发现这个 http://webcheatsheet.com/php/get_current_page_url.php

                          将以下代码添加到页面中:

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

                          您现在可以使用以下行获取当前页面 URL:

                          <?php
                            echo curPageURL();
                          ?>
                          

                          有时只需要获取页面名称。以下示例显示了如何执行此操作:

                          <?php
                          function curPageName() {
                           return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
                          }
                          
                          echo "The current page name is ".curPageName();
                          ?>
                          

                          【讨论】:

                            【解决方案21】:
                            $http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";
                            
                            $url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];
                            

                            【讨论】:

                              【解决方案22】:

                              函数调整为无警告执行:

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

                              【讨论】:

                                【解决方案23】:

                                我认为$_SERVER superglobal 拥有您正在寻找的信息。可能是这样的:

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

                                可以查看相关的PHP文档here

                                【讨论】:

                                • 这会一直重定向到用户现在所在的同一页面。如何解决此问题以重定向到主页?我在 apache,本地主机上。 php7
                                猜你喜欢
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 2011-08-05
                                • 2014-10-01
                                • 1970-01-01
                                • 2017-02-02
                                • 2021-12-28
                                • 2011-08-26
                                相关资源
                                最近更新 更多