How to Get Base URL from Full URL String in PHP

Base URL is used to create internal web page links dynamically in the website. You can get the base URL from the full URL string using PHP. The parse_url() function helps to parse components from URL in PHP. The base URL can be retrieved from a string using PHP parse_url() function.

The following code snippet shows how to get base URL from URL string with PHP.

  • PHP_URL_SCHEME – This component returns URL scheme (http/https).
  • PHP_URL_HOST – This componenet returns host name (example.com/www.example.com).
$url 'https://www.codexworld.com/how-to/get-current-url-php/'; 
$url parse_url($urlPHP_URL_SCHEME).'://'.parse_url($urlPHP_URL_HOST);
$base_url trim($url'/');

The above code ($base_url) will return the base URL from given string: https://www.codexworld.com

Leave a reply

keyboard_double_arrow_up