Thursday, March 19, 2009

PHP's _SERVER["DOCUMENT_ROOT"] no good for filesystem path with virtual directories

One thing that can bring a serious headache is if you use the PHP variable $_SERVER["DOCUMENT_ROOT"] to open files in the file system and your site is placed in an Virtual Directory in IIS.

This server variable points to the root of the server and this is not necessarily the path the virtual directory points to.

Of course this solution could work in the right conditions; hosted on a web server and placed in a physical directory under this path. However, if you want to have a flexible application and avoid issues if it is placed in a virtual directory, then do not use this variable.

An alternative could be to use:
dirname(__FILE__)
This method with the provided constant will return the directory where the current script file (also for included files) is located. Then you can point to this path relatively if it is a well known location such as your application root. Another benefit is that this constant is always available, as the _SERVER[] constants are depending on the host.

So here's my advise: try to avoid using the $_SERVER["DOCUMENT_ROOT"] variable for paths and use physical paths instead.

No comments: