How to get the base url in Drupal 8?

Member

by kadin , in category: PHP Frameworks , 2 years ago

How to get the base url in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by deron , a year 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>');


Member

by jasen , 8 months ago

@kadin 

In Drupal 8, you can retrieve the base URL using the following code:

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


This code uses the Drupal::request() method to get the current request object, and then calls the getSchemeAndHttpHost() method to retrieve the base URL.


You can use the $base_url variable to retrieve the base URL of your Drupal 8 site.