views:

65

answers:

3

Inside of a Drupal module I need to obtain the base path where the Drupal site is installed.

For example, if the drupal site is installed at: www.example.com/mysite/ then I want to get '/var/www/myseite'

If it is installed in: www.example.com/ then I want '/var/www'

What is the proper Drupal way to get this? I want to avoid PHP's server variables, as I read they are unreliable.

(Drupal 6 and Drupal 7)

+1  A: 

base_path() does this in both D6 and D7.

Scott Reynen
+2  A: 

Addition to Scott Reynen's answer:

In the page.tpl.php template, it's also available in the $base_path variable.

In many cases, you don't even need to know the base path, because the Drupal API functions add it themselves. For instance, to print a link, you could do this:

<?php print '<a href="' . base_path() . 'foo/bar">Foo Bar</a>'; ?>

But the "Drupal way" to do it is to use the l() function:

<?php print l('Foo Bar', 'foo/bar'); ?>

The l() function will automatically add the base path to the href.

marcvangend
Thanks, this is correct but I wasn't clear in my question. I want the document root. Edits above should help clarify.
Justin
I don't think that Drupal has a specific function for that. Drupal always tries to be agnostic to the server environment. The idea is that is you use the API functions, you shouldn't need to know the server path.
marcvangend
+1  A: 

To get the complete document root of the file system I use:

$_SERVER['DOCUMENT_ROOT'] . base_path()

On a Linux server you will get something like:

/var/www/html/www.example.com/mysite/

If you only use "base_path()", you will get only:

/mysite/

Same on Drupal 6 and 7.

FR6