Sunday, 7 August 2016

Get the Home URL or Site URL in PHP

It is very simple to get the Home URL or the Site URL in PHP. You have to just include a settings  file consisting of the functions that we create and include in all the pages so that if we call the function and echo the variable the output will be obtained.

Code:

function get_site_url()
{
    $currentPath = $_SERVER['PHP_SELF'];
    $pathInfo = pathinfo($currentPath);
    $hostName = $_SERVER['HTTP_HOST'];
    $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
    return $protocol.$hostName.$pathInfo['dirname']."/";
}

Usage:

Example: http://example.com/about
This is a Page you are currently accessing and we have to display the home page link in that page and if you access this function you will get the output as follows 

$url =get_site_url();
echo $url;
Output: http://example.com