I have been working on a project where sometimes I would have to get the domain from the site’s url so I can allow access to certain part of the site. Other times, I have parse the domain from referral url to see where the users are coming from.
Rather than writing two different php functions to get the domain name, I wanted to use one php function to get the job done fast.
Get Domain Name Function
/******[Get Main Domain URL Name - Start]******/
function GetDomainName($url)
{
$host = @parse_url($url, PHP_URL_HOST);
// If the URL can't be parsed, use the original URL
// Change to "return false" if you don't want that
if (!$host)
$host = $url;
// The "www." prefix isn't really needed if you're just using
// this to display the domain to the user
if (substr($host, 0, 4) == "www.")
$host = substr($host, 4);
// You might also want to limit the length if screen space is limited
if (strlen($host) > 50)
$host = substr($host, 0, 47) . '...';
return $host;
}
/******[Get Main Domain URL Name - End]******/
How Get Domain Name From PHP Function
To use this function, call it like any other php function.
Let’s suppose you want parse the domain name from a string, you would call the function like this:
$URL = “http://codewithmark.com/93/how-to-submit-a-wordpress-plugin/”;
Echo GetDomainName($URL);
//Result will be:
Codewithmark.com
Or to get the domain name from Referral URL you would call the function like this:
//get referrer
$RefURL =$_SERVER['HTTP_REFERER'];
Echo GetDomainName($RefURL);
If your referral site is – “http://codewithmark.com/how-to-submit-a-wordpress-plugin”
Result will be: codewithmark.com
Get Subdomain Name Of A URL
This function works great with subdomains as well.
For example, if your subdomain url is - http://demo.codewithmark.com/2015-10-26_KeyWordSpy/
It will return, demo.codewithmark.com
As you can see, how useful this php function could be in your web programming projects.