Get parent directory of running script
As of PHP 5.3.0 you can use __DIR__
for this purpose.
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__ FILE__).
See PHP Magic constants.
C:\www>php --version
PHP 5.5.6 (cli) (built: Nov 12 2013 11:33:44)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
C:\www>php -r "echo __DIR__;"
C:\www
If your script is located in /var/www/dir/index.php
then the following would return:
dirname(__FILE__); // /var/www/dir
or
dirname( dirname(__FILE__) ); // /var/www
Edit
This is a technique used in many frameworks to determine relative paths from the app_root.
File structure:
/var/ www/ index.php subdir/ library.php
index.php is my dispatcher/boostrap file that all requests are routed to:
define(ROOT_PATH, dirname(__FILE__) ); // /var/www
library.php is some file located an extra directory down and I need to determine the path relative to the app root (/var/www/).
$path_current = dirname( __FILE__ ); // /var/www/subdir
$path_relative = str_replace(ROOT_PATH, '', $path_current); // /subdir
There's probably a better way to calculate the relative path then str_replace()
but you get the idea.