File Directory Constants
suggest changeCurrent file
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";
Current directory
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: " , __DIR__ , "\n";
To get the absolute path to the directory where the current file is located, use dirname(__FILE__).
echo "Our script is located in: " , 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__); // the name must be a string
// somefile.php looks for views:
$view = 'page';
$viewFile = BASEDIR . '/views/' . $view;
Separators
Windows accepts / in paths, so DIRECTORY_SEPARATOR matters most when you parse a path the system returned.
Besides the magic constants, PHP defines:
DIRECTORY_SEPARATOR,/on Unix-like systems and\on Windows. The views path can be built with it:
$view = 'page';
$viewFile = BASEDIR . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view;
PATH_SEPARATOR, used between entries in aPATH-style list. It is;on Windows and:elsewhere.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents