6

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)

Justin
  • 2,914
  • 5
  • 41
  • 66

5 Answers5

11

In Drupal 7, there is a new constant called DRUPAL_ROOT which you can use for this.

Berdir
  • 6,881
  • 2
  • 26
  • 38
5

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
  • 3,157
  • 3
  • 24
  • 28
2

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
  • 5,592
  • 4
  • 22
  • 32
  • Thanks, this is correct but I wasn't clear in my question. I want the document root. Edits above should help clarify. – Justin Oct 18 '10 at 13:17
  • 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 Oct 18 '10 at 15:31
1

base_path() does this in both D6 and D7.

Scott Reynen
  • 3,530
  • 18
  • 17
0

You can use DRUPAL_ROOT constant for that.

shumer
  • 61
  • 2