PHP Get root domain name method rollup

Source: Internet
Author: User

If you simply get the current access to your page's domain name, we only need to use PHP function Http_host can be done, if it is to extract the URL root domain name is required regular, below to look at a few concrete examples.

It is very simple to get the current domain name:

The code is as follows:


Get the current domain name:

echo $_server[' server_name '];

Get the source URL, that is, click here to the previous page URL

echo $_server["Http_referer"];

$_server[' Request_uri '];//get the suffix of the current domain name

$_server[' Http_host '];//get the current domain name

DirName (__file__)//Get the physical path of the current file

DirName (__file__). " /.. /";//Get the physical path to the current file


Example 1

The code is as follows:

function Geturlroot ($url) {


$url = $url. "/";


Preg_match ("/(w*)://)?" w*.? ([w|-]*. (||||com|net|cn|org|asia|tel|mobi|me|tv|biz|cc|name|info))

", $url, $ohurl);


if ($ohurl [3] = = ") {

Preg_match ("/(d+.) {3}d+)//", $url, $ohip);

return $ohip [1];


return $ohurl [3];


Example 2

The code is as follows:


* Get root domain

* @param type $domain domain name

* @return string returns the root domain name


function Geturltodomain ($domain) {

$re _domain = ';

$domain _postfix_cn_array = Array ("com", "net", "org", "gov", "edu", "", "cn");

$array _domain = Explode (".", $domain);

$array _num = count ($array _domain)-1;

if ($array _domain[$array _num] = = ' cn ') {

if (In_array ($array _domain[$array _num-1], $domain _postfix_cn_array)) {

$re _domain = $array _domain[$array _num-2]. "." . $array _domain[$array _num-1]. "." . $array _domain[$array _num];

} else {

$re _domain = $array _domain[$array _num-1]. "." . $array _domain[$array _num];


} else {

$re _domain = $array _domain[$array _num-1]. "." . $array _domain[$array _num];


return $re _domain;


Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.