You can get the name of the current PHP file (with the absolute path) using the
__FILE__ magic constant. This is most often used as a logging/debugging technique.
echo "We are in the file:" , __FILE__ , "\n";
To get the absolute path to the directory where the current file is located use the
__DIR__ magic constant.
echo "Our script is located in the:" , __DIR__ , "\n";
To get the absolute path to the directory where the current file is located, use
echo "Our script is located in the:" , dirname(__FILE__) , "\n";
Getting current directory is often used by PHP frameworks to set a base directory:
// index.php of the framework define(BASEDIR, __DIR__); // using magic constant to define normal constant
// somefile.php looks for views: $view = 'page'; $viewFile = BASEDIR . '/views/' . $view;
Windows system perfectly understands the
/in paths so the
DIRECTORY_SEPARATORis used mainly when parsing paths.
Besides magic constants PHP also adds some fixed constants for working with paths:
DIRECTORY_SEPARATORconstant for separating directories in a path. Takes value
/on *nix, and
\on Windows. The example with views can be rewritten with:
$view = 'page'; $viewFile = BASEDIR . DIRECTORY_SEPARATOR .'views' . DIRECTORY_SEPARATOR . $view;
PATH_SEPARATORconstant for separating paths in the
$PATHenvironment variable. It is