PHP: How to get Main or Base URL?

Suppose you are on a page : http://example.com/category/php/
Now, the base URL or the main URL for the above link is : http://example.com

Similarly, in the case of local machine (localhost),
Suppose you are in the page : http://localhost/myproject/index.php?id=8
Here, the base or main URL is : http://localhost/myproject

Below is the code to get main or base URL from any URL link or path:-


/**
 * Suppose, you are browsing in your localhost 
 * http://localhost/myproject/index.php?id=8
 */
function getBaseUrl() 
{
	// output: /myproject/index.php
	$currentPath = $_SERVER['PHP_SELF']; 
	
	// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
	$pathInfo = pathinfo($currentPath); 
	
	// output: localhost
	$hostName = $_SERVER['HTTP_HOST']; 
	
	// output: http://
	$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
	
	// return: http://localhost/myproject/
	return $protocol.$hostName.$pathInfo['dirname']."/";
}

Hope this helps. Thanks.