1

(Drupal 7.22) We need to create a menu link to an external site, "https://example.com/some/path" /some/path is static, whereas "https://example.com" depends on site instance, such as

web-dev.example.com

web-qa.exmple.com

web-rc.example.com

I would think that this could be accomplished with $GLOBALS['base_root']; for example: $url = $GLOBALS['base_root'] . '/some/path';

On local (laptop) $GLOBALS['base_root'] resolves correctly, but on CentoOS $GLOBALS['base_root'] resolves to [http://default]

How do we dynamically get the actual current site domain?
This can't be so hard, what are we missing?

2 Answers 2

9

If this is a fully bootstrapped Drupal site, the superglobal $base_url, should get you what you want. See: https://api.drupal.org/api/drupal/developer!globals.php/global/base_url/7

However, these globals are not initialized until Drupal is fully bootstrapped.

If you need to sniff the base URL before Drupal is fully bootstrapped you can use the PHP $_SERVER superglobal.

For example:

function _get_base_url(){
  $protocol = ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != "off")) ? "https" : "http";
  return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
4
  • Yea, I'm still missing something here. In an install hook, I have watchdog('menu_link-base_url', $GLOBALS['base_url']); watchdog('menu_link-base_path', $GLOBALS['base_path']); watchdog('menu_link-base_root', $GLOBALS['base_root']); and that returns: "default" (base_url) "/" (base_path) and "default" (base_root), although the $GLOBALS['base_url'] and $GLOBALS['base_root'] correctly return the current site domain when referenced from page.tpl.php (for debugging). Why different from an install hook on the same site?
    – August1914
    Jul 11, 2013 at 19:17
  • I got what I needed by setting $base_url in settings.php: $base_url = 'example.com'; But it means we need to manage settings.php for different deployment environments Is this the only way the $base_url is set, or does it depend on other php or server settings as well?
    – August1914
    Jul 11, 2013 at 20:09
  • I think it's fine to have different settings.php files for different environments. Usually I never commit settings.php file to any version control systems.
    – Beebee
    Jul 12, 2013 at 10:35
  • If you're installing the module via drush, you may get a default url. If so, you can use a drush alias, or pass the drush parameter --uri=example.com Jul 12, 2013 at 11:49
1

For the case when Drupal is fully bootstrapped, that is when $base_url works, the url() function is a potentially more elegant alternative:

$make_absolute = array('absolute' => TRUE);
$url = url("some/path", $make_absolute);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.