File Directory Constants

suggest change

Current 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:

$view = 'page';
$viewFile = BASEDIR . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents