What is the correct way to get the document root installed by Drupal?

Inside the Drupal module, I need to get the base path where the Drupal website is installed.

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

If it is installed at: www.example.com/ then I want to '/ Var / WWW

What is the correct way for Drupal to get this? I want to avoid PHP server variables since I read that they are unreliable.

(Drupal 6 and Drupal 7)

+6
php drupal drupal-7 drupal-6
source share
5 answers

Drupal 7 has a new constant called DRUPAL_ROOT that you can use to do this.

+10
source share

To get the full root of a file system document, 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 use only "base_path ()", you will only get:

 /mysite/ 

Same thing on Drupal 6 and 7.

+5
source share

Addition to Scott Reinen's answer:

In the page.tpl.php template, it is 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 example, to print a link, you can do this:

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

But the โ€œDrupal wayโ€ for this is to use the l () function:

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

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

+2
source share

base_path () does this in both D6 and D7.

+1
source share

You can use the constant DRUPAL_ROOT for this.

0
source share

All Articles