简体   繁体   中英

PHP get website root absolute URL in server?

I rely heavily in $_SERVER["DOCUMENT_ROOT"] to get absolute paths. However this doesn't work for sites which URLs don't point to the root.

I have sites stored in folders such as:

  • site1
  • site2

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'] .

Update

The website seems to be directory "mounted" on that folder, so SCRIPT_NAME will obviously be / .

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.

Update 2

There's no single index.php controller for the whole site, so that won't work either.

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:

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.

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

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

or use the getcwd() . it gets the current working directory of your application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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