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 the:" , __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 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;
# Separators
> Windows system perfectly understands the `/` in paths so the
> `DIRECTORY_SEPARATOR` is used mainly when parsing paths.
Besides magic constants PHP also adds some fixed constants for working with paths:
* `DIRECTORY_SEPARATOR` constant 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; ```
- Rarely used
PATH_SEPARATOR
constant for separating paths in the$PATH
environment variable. It is;
on Windows,:
otherwise
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents