How to Get Domain Name from URL in PHP

Parse domain name from URL is used in many cases in the web project. In this short tutorial, we’ll provide a simple code snippet to get domain name from URL in PHP. Using our example script, you’ll be able to extract only the domain name from any type of URL.

All PHP code are group together in getDomain() function. The $url param should be passed to getDomain() function, from which you want to get the domain name. getDomain() function returns the domain name if found and FALSE if not found.

function getDomain($url){
$pieces parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';

getDomain(""); // outputs ''
echo getDomain(""); // outputs ''
echo getDomain(""); // outputs ''

Leave a reply

CodexWorld Newsletter

Subscribe CodexWorld updates via email and get every new post delivered to your inbox.