$_SERVER['HTTP_HOST'] contains port number too =/
Asked Answered
F

2

11

I don't know maybe it's a bug.

I have 2 virutalhosts on my server.

virtualhost1.com virtualhost2.com

if i open virtualhost1.com with port 80 (virtualhost1.com:80)

$_SERVER['HTTP_HOST']='virtualhost1.com';

but if i open virtualhost2.com:80

$_SERVER['HTTP_HOST']='virtualhost2.com:80'; // NOTE: with port number

Can I know why?

Festatus answered 21/12, 2010 at 23:11 Comment(2)
I suggest posting your VirtualHost definitions.Peacetime
And I suggest rtfm php.net/manual/en/reserved.variables.server.phpAmar
W
21

The value of $_SERVER['HTTP_HOST'] is taken directly from the Host: HTTP request header. It appears the requesting client is filling it in that way.

I suggest using $_SERVER['SERVER_NAME'] instead as its value will be set from your virtual host config. However, as Flimm notes below, even the reliability of SERVER_NAME can still be dependent on server config (check out this answer for more info on that).

Wileywilfong answered 21/12, 2010 at 23:21 Comment(1)
Note that it's a bit more complicated than that, $_SERVER['SERVER_NAME'] can't always be trusted. See this questionChristoforo
S
1

Following function always return real host (user typed host) without port and it's almost reliable:

function getRealHost(){
   list($realHost,)=explode(':',$_SERVER['HTTP_HOST']);
   return $realHost;
}
Soutache answered 20/5, 2016 at 13:17 Comment(2)
Just return strstr($_SERVER['HTTP_HOST'], ':', true);Hallie
@lawrence-cherone this will return an empty string if no ':' character is found. It's better to use strtok($_SERVER['HTTP_HOST'], ':');Trichomonad

© 2022 - 2024 — McMap. All rights reserved.