__DIR__ and path management
Learn to manage file paths safely with the __DIR__ magic constant.
The __DIR__ magic constant
The __DIR__ magic constant in PHP returns the full (absolute) path of the directory that contains the file where it is used. In other words, it is the directory of the calling file.
This is used to build safe paths when including files. Instead of include 'lib/db.php'; you can write include __DIR__ . '/lib/db.php';, and the script finds the right file no matter which directory it runs from. Relative paths (../lib/db.php) depend on the working directory of the calling script and may differ between CLI and web. __DIR__ always gives the same result.
Relative and absolute paths
When including files you can use two kinds of paths: relative (lib/db.php, ../header.php) and absolute (/var/www/app/lib/db.php). A relative path is resolved against the current working directory (cwd), which may be the terminal directory in CLI or the script directory on the web.
This ambiguity causes errors. A path that starts with __DIR__ is always the same: include __DIR__ . '/../lib/db.php'; goes up one level from the script's directory and then into the lib folder. In multi-layer projects, using __DIR__ keeps paths consistent.
Exercise Create partial.php with __DIR__ and include it
Assign the path __DIR__ . "/partial.php" to $file. Write the file with file_put_contents($file, "<?php echo 'Partial content'; ?>"). Then include the file with include $file;.
Show example solution
First set $file = __DIR__ . "/partial.php";. Then write file_put_contents($file, "<?php echo 'Partial content'; ?>");. Finally add include $file;.
Example solution:
<?php
// Create partial.php with __DIR__ and include it
$file = __DIR__ . "/partial.php";
file_put_contents($file, "<?php echo 'Partial content'; ?>");
include $file;
Test yourself
-
What does the __DIR__ magic constant return?
- The URL of the running script
- The root directory of the server
- The directory where PHP is installed
- The directory of the running file
Show answer
The directory of the running file — Correct. __DIR__ returns the absolute path of the directory of the file that uses it.
-
Complete the path with __DIR__
$file = ____ . "/lib/db.php";Show answer
$file = __DIR__ . "/lib/db.php"; -
Match path expressions
- __DIR__
- File's directory
- __FILE__
- File's full path
- sys_get_temp_dir()
- Temp directory
- /var/www/app
- Absolute path