What is the correct way to obtain the Drupal installed document root?
سؤال
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)
المحلول
In Drupal 7, there is a new constant called DRUPAL_ROOT which you can use for this.
نصائح أخرى
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.
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.
base_path() does this in both D6 and D7.
You can use DRUPAL_ROOT constant for that.