Les exemples de cet article résument les méthodes d'obtention du nom de domaine racine en PHP et les partagent avec vous pour votre référence. La méthode d'implémentation spécifique est la suivante :
Si vous obtenez simplement le nom de domaine qui visite actuellement votre page, il nous suffit d'utiliser la fonction HTTP_HOST en php pour le faire. S'il s'agit d'extraire l'url, le nom de domaine racine doit être régulier. Jetons un coup d'œil à quelques exemples spécifiques.
Il est très simple d'obtenir le nom de domaine actuel :
Le code est le suivant :
1 2 3 4 5 6 7 8 9 10 | <?php
echo $_SERVER ['SERVER_NAME'];
echo $_SERVER [ "HTTP_REFERER" ];
$_SERVER ['REQUEST_URI'];
$_SERVER ['HTTP_HOST'];
dirname(FILE);
dirname(FILE). "/../" ;
?>
|
Copier après la connexion
Exemple 1
Le code est le suivant :
1 2 3 4 5 6 7 8 9 10 11 12 13 | function getUrlRoot( $url ){
#添加头部和尾巴
$url = $url . "/" ;
#判断域名
preg_match("/((\w*):\/\/)?\w*\.?([\w|-]*\.(com.cn|net.cn|gov.cn|org.cn|com|net|cn|org|asia|tel|mobi|me|tv|biz|cc|name|info))
\
#判断IP
if ( $ohurl [3] == ''){
preg_match( "/((\d+\.){3}\d+)\//" , $url , $ohip );
return $ohip [1];
}
return $ohurl [3];
}
|
Copier après la connexion
Exemple 2
Le code est le suivant :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function GetUrlToDomain( $domain ) {
$re_domain = '';
$domain_postfix_cn_array = array ( "com" , "net" , "org" , "gov" , "edu" , "com.cn" , "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 ;
}
|
Copier après la connexion
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!