Many web applications ask the person doing the installation to fill in a few configuration settings. These are often important pieces of information that tell the web app about the environment in which it will operate, and how the administrator would like the application to behave. It is not unheard-of to ask the person to edit some code – perhaps an initialization file – in order to input this information. When this is the case, I recommend that you keep the amount of code edited by the user to a minimum and try make your web application as intelligent as possible when it comes to discerning configuration and environment settings.
One of the most common configuration settings that a web application will ask for is the path to its base (or “root”) directory. This helps the application locate other vital components, such as templates, code libraries, and data files. PHP has a built-in function called dirname that makes it very easy for your web app to automatically figure out its own base directory.
How to use the dirname function
I like to use dirname in conjunction with the constant __FILE__ to figure out the script or application’s base directory. The magical constant __FILE__ (”file” in upper case, both preceded and followed by two underscores) gives the location of the PHP script. This constant is especially helpful in included or required scripts, because it gives the location of the PHP script file in which it lives, rather than the location of the script that issued the include or require directive. Pass __FILE__ to the dirname function, and you get back the directory in which your script is located.
Example
Here is a screenshot of a common directory layout I utilize when building a web application in PHP:
I can place define('MY_PATH', dirname(dirname(__FILE__))); in init.inc.php, and the constant MY_PATH would then hold the path to the base directory of my web application (”mysite”). Any PHP script that includes or requires that initialization file can then use the MY_PATH constant to refer to other files throughout the web application’s directory structure.




