如何获取网站的基本网址而不手动设置?

时间:2015-08-13 13:50:33

标签: php url uri superglobals

我正在努力实现一种方法,通过该方法我可以获得网站的基本网址,而无需手动定义,也不管以后添加任何其他附加查询字符串或文件夹

实施例

如果网址是

  

http://localhost/testsite/action/login

     

http://192.154.15.02/~testuser/testsite?action=login

输出应为

  

http://localhost/testsite

     

http://192.154.15.02/~testuser/testsite

分别

我尝试过使用此功能及其他相关变体

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

但它总是根据网址中的添加值而改变。

我可以请一些帮助。

由于

1 个答案:

答案 0 :(得分:0)

对于绝对路径,定义常量有时很有用:

  // which page are we on?  eg /some/path/to/script.php
  if( ! defined( 'WEB_PATH' ) ) define('WEB_PATH', $_SERVER['PHP_SELF']);

  // web root dir. eg /some/path/to
  //if( ! defined( 'WEB_ROOT' ) ) define('WEB_ROOT', dirname(WEB_PATH));
  if( ! defined( 'WEB_ROOT' ) ) {
          $path = dirname(WEB_PATH);
          // avoid "//" at root
          if ( $path == '/' ) $path = '';
          define('WEB_ROOT', $path);
  }


  // what is the file name only?  // eg script.php
  if( ! defined( 'WEB_FILE' ) ) define('WEB_FILE', basename(WEB_PATH));

  // physical file path (system).  eg: /var/www/html/yoursite
  if( ! defined( 'ABS_ROOT' ) ) define('ABS_ROOT', dirname(__FILE__));