Summary of Methods of Obtaining Domain Name by PHP

  • 2021-07-26 06:56:58
  • OfStack

This paper summarizes the method of obtaining domain name by PHP. Share it for your reference. The specific implementation method is as follows:

Method 1 (using system variables)

// Disadvantages do not use passed addresses and hosts that do not support system variables 
echo $_SERVER['HTTP_HOST'];
   

Method 2 (with its own function)

$url = 'https://www.ofstack.com/index.php?referer=ofstack.com';     
$arr_url = parse_url($url);    
echo $arr_url['host'];

Method 3 (write your own function)

function getdomain($url)              
{      
    $url = str_replace('http://', " ,$url);   // If there is http Prefix , Remove
    $pos = strpos($url,'/');      
    if($pos === false)      
      {      
          return $url;      
      }else    
      {      
          return substr($url, 0, $pos);      
      }      
}      
echo getdomain($url);

Method 4 (using regularity)

preg_match("/^(http://)?([^/]+)/i", $url, $arr_domain);     
echo $arr_domain[2];

I hope this article is helpful to everyone's PHP programming.


Related articles: