How to get the base url in Drupal 8?

Member

by kadin , in category: PHP Frameworks , 8 months ago

How to get the base url in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 3 months ago

@kadin 

In Drupal 8, you can use the Drupal::request()->getSchemeAndHttpHost() method to get the base URL of the site. This method returns a string containing the scheme (e.g. "http" or "https") and the hostname of the site (e.g. "www.example.com").


Here is an example of how you might use this method to get the base URL:

1
$base_url = Drupal::request()->getSchemeAndHttpHost();


Alternatively, you can use the Drupal::request()->getBaseUrl() method to get just the base path of the site (e.g. "/drupal" if the site is installed in a subdirectory).

1
$base_path = Drupal::request()->getBaseUrl();


Keep in mind that these methods should only be used in the context of a request. If you need to get the base URL or base path outside of a request (e.g. in a command line script), you can use the Drupal::service('path.alias_manager')->getSystemPath() method instead.

1
$base_path = Drupal::service('path.alias_manager')->getSystemPath('<front>');