Monday, August 13, 2007

PHP DOCUMENT_ROOT in IIS (Windows servers)

If you've been searching for this page then you most certainly don't need me to explain anything, you just want the goodies. So here it is -just add the following code to the beginning of your PHP application and use $_SERVER['DOCUMENT_ROOT'] as you wish...

// let's make sure the $_SERVER['DOCUMENT_ROOT'] variable is set
if(!isset($_SERVER['DOCUMENT_ROOT'])){ if(isset($_SERVER['SCRIPT_FILENAME'])){
$_SERVER['DOCUMENT_ROOT'] =
str_replace( '\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])));
}; };
if(!isset($_SERVER['
DOCUMENT_ROOT'])){ if(isset($_SERVER['PATH_TRANSLATED'])){
$_SERVER['
DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0-strlen($_SERVER['PHP_SELF'])));
}; };
//
$_SERVER['DOCUMENT_ROOT'] is now set - you can use it as usual...
And now, for those of you who want to know what this is all about:

Being an ASP developer, I am quite comfortable with the use of Server.MapPath. I can find the physical root of the website very easily like this...
Dim sRootOfWebsite
sRootOfWebsite = Server.MapPath("/")
...PHP on the other hand doesn't offer such a simple way of doing this, but it does supply a range of pre-defined run-time variables that make it development easy. Unfortunately, these are not so constant in PHP and depend on the server configuration. Many hosts purposely turn off certain variables for security reasons.

The most common example is the $_SERVER['DOCUMENT_ROOT'] variable, which is not available on IIS (Windows Servers). Which is what the code at the top of this article is all about.

For a proper explanation of the problem - and a much better read - see Finding the document root in PHP.

3 comments:

Halil said...

You have saved my life !

I use DOCUMENT_ROOT regularly, to include files and to set proper paths to editor-returned image paths (like from fckeditor's file browser, or from a custom one.).

Hence we would like to see the image both in administrator page and in the actual page, we must set a absolute path starting with '/' like '/mySite/img/user/etc.jpg'.

In order to implement this in most cross-directory and cross-server form, I need a DOCROOT variable.

And PHP's $_SERVER['DOCUMENT_ROOT'] used to provide this, until I abruptly started to get empty values (our IIS server).

So I was thinking hard to get a docroot out of some globals, and you saved me a lot of trouble.

Thank you very much.

halil [dot] ozgur [at] gmail.com

Diego A. said...

Hi Halil,

I'm glad this helped. I have the exact same problem using FCK editor and the image manager plugin, which is why I found a solution to this problem.

I realised there wasn't much information available so I thought I'd post it here and help others with the same problem...

Thanks for the comments,
Diego A.

Iacob said...

Just two words man: THANK YOU!