How to get real host or server name in PHP

How to get a real hostname without using $ _SERVER ['SERVER_NAME'] in PHP? Is there an even more reliable way to get it?

I created a function that gets the host name from the domain path.

I would like to avoid using the variable $ _SERVER ['SERVER_NAME'], because it can be faked by sending the modified headers to the HTTP request.

This is my current implementation (this works if the path has an actual domain name in it. For example: /vhosts/website.com/public_html):

function getServerName() {
 $path = realpath(__FILE__);
 $url = array();
 preg_match_all("/\/[a-z0-9-]+(\.[a-z0-9-]+)+/i", $path, $url);
 // 4 is minimum requirement for the address (e.g: http://www.in.tv)
 if (strlen($url[0][0]) > 4) {
  $result = str_replace("/", "", $url[0][0]);
  return $result;
 }
 else
  return false;
}

Thank!

+3
source share
6 answers

Edit: as pointed out by Gumbo, the original poster probably means HTTP_HOST, not HOST_NAME. Otherwise my answer is simple.

HTTP_HOST , . ! $_SERVER ['HTTP_HOST']. ? , -. , , PHP Apache.

<?php

$request_headers = apache_request_headers();
echo $request_headers['Host'];

?>

, - ? , ?

, HTTP- $_SERVER ['HTTP_HOST'] . , : , . , - ( ), , , .

+1

, , $_SERVER['SERVER_NAME']. , , , Gumbo .

+6

, , ,

$_SERVER['HTTP_HOST'];

, HTTP, , HTTP.

, :

$_SERVER['SERVER_NAME']

?

+3

, ( ), , .

$host = php_uname( 'n' );

Apache, , / ( , ). ServerName ServerAlias.

+3

$_SERVER['HTTP_HOST'] - IT IS . http. , vhost , $_SERVER['SERVER_NAME'], .

( __FILE__), ( ).

, script var_dump($_SERVER), , - - . -, , - php.

/ :. , $_SERVER['SERVER_NAME'] , apache UseCanonicalName off ( , , , Plesk ). __FILE__ ( ). , (SQL, JavaScript), php , SERVER_NAME , , .

+2

No. This is the goal of the $ _SERVER variables. If you want to get HOST_NAME from the path, you must first get PATH from $ _SERVER ['HTTP_HOST']

+1
source

Source: https://habr.com/ru/post/1730000/


All Articles