base_path

5 common.inc base_path()
6 common.inc base_path()
7 common.inc base_path()
8 common.inc base_path()

Returns the base URL path of the Drupal installation. At the very least, this will always default to /.

20 calls to base_path()

2 string references to 'base_path'

File

includes/common.inc, line 1760
Common functions that many Drupal modules will need to reference.

Code

function base_path() {
  return $GLOBALS['base_path'];
}

Comments

Safe way to get DOCUMENT_ROOT

base_path returns the base URL path, not the local path.

Apparently $_SERVER['DOCUMENT_ROOT'] isn't safe as there seems to be situations where it is not set, see http://drupal.org/node/518460 and http://drupal.org/node/329710 for some discussions about it.

The proper way to set this would probably be something like

$GLOBALS['base_local_path'] = dirname(__FILE__);

in main index.php file.

As I won't touch it here is a fix that JUST WORKStm (code from http://drupal.org/node/518460#comment-1808184):

/**
* Get the document root for the current Drupal installation.
* $_SERVER['DOCUMENT_ROOT'] is not reliable across all
* systems, so we need a way to get the correct value.
*
* @return (string)
*/
function YOURMODULE_document_root() {
  $absolute_dir = dirname(__FILE__);
  $relative_dir = drupal_get_path('module', 'YOURMODULE');
  return substr($absolute_dir, 0, -1 * (1 + strlen($relative_dir)));
}

very handy working on MAMP

I was having difficulties grabbing the right location of the files directory on localhost (MAMP) and production - this solved it - thanks.

A non-module specific way

A non-module specific (and simpler) way would be
return getcwd().'/';
(see http://drupal.org/node/363013)
or
return realpath('.'.base_path()).'/';
in case we have actually chdirred...

Indeed, many people ask for the root and many incorrectly answer that base_path() would be the solution. Perhaps we can have a Drupal function $base_root...?

realpath('./')

base_path() and $base_path return / in my sites. No use when trying to read a file. realpath('./') worked. It picks up the path to index.php. I can then append the path provided by drupal_get_path().

Login or register to post comments