Learn how to get the domain from a URL or easily parse domain from a string with this easy to use php function.
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.
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;
}
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
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.
You spend weeks building a project.
Your client pays you.
Then the income stops.
Meanwhile, other developers are turning similar skills into products that generate revenue month after month.
A SaaS, plugin, web app, or digital product can continue bringing in customers long after it's launched.
The real question isn't whether you can build one.
It's how much money you're leaving on the table by not starting.
Learn How To Build Monthly Income →