简体   繁体   English

PHP在服务器中获取网站根绝对URL?

[英]PHP get website root absolute URL in server?

I rely heavily in $_SERVER["DOCUMENT_ROOT"] to get absolute paths. 我非常依赖$_SERVER["DOCUMENT_ROOT"]来获取绝对路径。 However this doesn't work for sites which URLs don't point to the root. 但是,这不适用于URL未指向根的站点。

I have sites stored in folders such as: 我将网站存储在以下文件夹中:

  • site1 SITE1
  • site2 站点2

all directly inside the root. 都直接在根内。 Is there a way to get the path in the server where the current site root is? 有没有办法在服务器中获取当前站点根目录的路径?

It should return: 它应该返回:

   /var/chroot/home/content/02/6945202/html/site1 // If the site is stored in folder 'site1'
   /var/chroot/home/content/02/6945202/html // If the site is stored in the root

You can simply append dirname($_SERVER['SCRIPT_NAME']) to $_SERVER['DOCUMENT_ROOT'] . 您只需将dirname($_SERVER['SCRIPT_NAME'])附加到$_SERVER['DOCUMENT_ROOT']

Update 更新

The website seems to be directory "mounted" on that folder, so SCRIPT_NAME will obviously be / . 该网站似乎是“挂载”在该文件夹上的目录,因此SCRIPT_NAME显然是/

So, to make this work you have to use either __DIR__ or dirname(__FILE__) to find out where your script is located in the file system. 因此,要完成这项工作,您必须使用__DIR__dirname(__FILE__)来查找脚本在文件系统中的位置。

Update 2 更新2

There's no single index.php controller for the whole site, so that won't work either. 整个站点没有单一的index.php控制器,因此也不起作用。

The following expression does a string "subtraction" to find the common path. 下面的表达式用字符串“减法”来查找公共路径。 You have a known prefix (document root), an unknown (the root folder) and a known suffix (the script path), so to find the first two, you take the full absolute path ( __FILE__ ) and subtract the known suffix: 你有一个已知的前缀(文档根),一个未知的(根文件夹)和一个已知的后缀(脚本路径),所以要找到前两个,你取完整的绝对路径( __FILE__ )并减去已知的后缀:

substr(__FILE__, 0, -strlen($_SERVER['SCRIPT_NAME']));

If included files need this value, you must store this in a constant first before including the dependent scripts. 如果包含的文件需要此值,则必须先将其存储在常量中,然后才能包含依赖脚本。 .

对于未来的谷歌,这对我也有用

substr(substr(__FILE__, strlen(realpath($_SERVER['DOCUMENT_ROOT']))), 0, - strlen(basename(__FILE__)));

Just use getcwd() for the current absolute server path of the folder the current script is in. 只需使用getcwd()获取当前脚本所在文件夹的当前绝对服务器路径。

You can define a constant at the top of your website so that the rest of the website can rely on that path. 您可以在网站顶部定义一个常量,以便网站的其余部分可以依赖该路径。

define('MY_SERVER_PATH', getcwd());

use the following method to get the absolute root url from your server settings 使用以下方法从服务器设置中获取绝对根URL

   str_replace($_SERVER['DOCUMENT_ROOT']."/",$_SERVER['PHPRC'],$_SERVER['REAL_DOCUMENT_ROOT'])

or use the getcwd() . 或使用getcwd() it gets the current working directory of your application 它获取应用程序的当前工作目录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM