Is there a way in PHP to get the hostname and document root from the server? I'd like to do this without storing them as variables in your php code. I am reluctant to use $_SERVER because I have heard it is not reliable and subject to attack. How can this be done on a virtual host? Does a reliable and safe method exist?
A:
Like you mentioned, you have access to : http://php.net/manual/en/reserved.variables.php There's a breakdown here of using realpath() and $_SERVER to get the doc root: http://www.helicron.net/php/
Also, you could exec('hostname') or something similar to get the hostname.
Mr-sk
2010-01-15 18:07:02
My suspicion is that won't work for virtual hosts.
SorcyCat
2010-01-15 18:19:54
+1
A:
$_SERVER['DOCUMENT_ROOT']
is reliable but $_SERVER['SERVER_NAME']
isn’t (see Chris Shiflett’s SERVER_NAME Versus HTTP_HOST). Only if Apache’s UseCanonicalName
is enabled the canonical name is shown.
Gumbo
2010-01-15 18:07:35
I accepted your solution because it sparked a conversation with my host about if I could safely use SERVER_NAME.
SorcyCat
2010-01-22 15:25:20
+3
A:
You could try
$docroot = getenv("DOCUMENT_ROOT");
getenv
lets you access environment variables. You can see all variables that are available by printing phpinfo
. Maybe apache_getenv
also helps.
Felix Kling
2010-01-15 18:09:10
To be honest, I don't about windows, but it is not hard just to try it ;)
Felix Kling
2010-01-15 18:15:04