Monday, 2 February 2015

Get Domain Name From URL

Get Domain Name From URL

Here is a function to perform the simple task of getting the domain name from a URL. The function requires a valid URL to work, and if an invalid URL, or a URL without a hostname and scheme is provide, the function will return false.

<?php
function getDomain($url)
{
    if(
filter_var($urlFILTER_VALIDATE_URLFILTER_FLAG_HOST_REQUIRED) === FALSE)
    {
        return 
false;
    }
    
/*** get the url parts ***/
    
$parts parse_url($url);
    
/*** return the host domain ***/
    
return $parts['scheme'].'://'.$parts['host'];
}
?>

EXAMPLE CODE


<?php

$url 
'http://phpro.org/classes/Phproogle-Docs.html';

echo 
getDomain($url);
?>

0 comments:

Post a Comment