Skip to content

Instantly share code, notes, and snippets.

@locvfx
Created September 6, 2023 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save locvfx/7b55f5f5f1e63d86ea12ad6c6bfb1840 to your computer and use it in GitHub Desktop.
Save locvfx/7b55f5f5f1e63d86ea12ad6c6bfb1840 to your computer and use it in GitHub Desktop.
get hostname in PHP
function getHost($url) {
$parseUrl = parse_url(trim($url));
if(isset($parseUrl['host']))
{
$host = $parseUrl['host'];
}
else
{
$path = explode('/', $parseUrl['path']);
$host = $path[0];
}
return trim($host);
}
echo getHost("http://example.com/anything.html"); // example.com
echo getHost("http://www.example.net/directory/post.php"); // www.example.net
echo getHost("https://example.co.uk"); // example.co.uk
echo getHost("www.example.net"); // example.net
echo getHost("subdomain.example.net/anything"); // subdomain.example.net
echo getHost("example.net"); // example.net
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment