Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get website root absolute URL in server?

Tags:

php

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
like image 502
lisovaccaro Avatar asked Jun 07 '12 04:06

lisovaccaro


People also ask

How can I get root URL in PHP?

$pathInPieces = explode('/', $_SERVER['DOCUMENT_ROOT']); echo $pathInPieces[0]; This will output the server's root directory.

How do I find the root of a URL?

The root URL is the section between the colon-slash-slash (://) and the next slash (/), omitting any port number (:portno). That is, if you want to license your server at http://www.somebody.com:1080 the root URL is “www.somebody.com”.

What is $_ server [' DOCUMENT_ROOT ']?

$_SERVER['DOCUMENT_ROOT'] returns. The document root directory under which the current script is executing, as defined in the server's configuration file.


3 Answers

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

like image 172
Ja͢ck Avatar answered Oct 23 '22 00:10

Ja͢ck


For future googlers, this also works for me

substr(substr(__FILE__, strlen(realpath($_SERVER['DOCUMENT_ROOT']))), 0, - strlen(basename(__FILE__)));
like image 34
Ergec Avatar answered Oct 23 '22 01:10

Ergec


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());
like image 39
Ozzy Avatar answered Oct 23 '22 01:10

Ozzy