A common beginner bug: require "config.php" works on one page and breaks on another. The reason is how PHP finds files.
Relative paths depend on where you started
A path like "config.php" is searched in the include_path folders, then in the folder of the script that is running, and the “current working directory”. When page A in one folder includes a file that itself includes "config.php", PHP may look in the wrong folder.
__DIR__ is always right
__DIR__ is a magic constant that holds the full path of the folder that contains the current file. It never depends on where the request started.
<?php
echo basename(__DIR__) !== "" ? "__DIR__ is always set" : "";
__DIR__ is always set
Use it to build a path:
<?php
require __DIR__ . "/config.php"; // same folder
require __DIR__ . "/../includes/functions.php"; // one folder up
Going up with dirname()
<?php
$path = "/var/www/my-site/public/index.php";
echo dirname($path) . "\n";
echo dirname($path, 2);
/var/www/my-site/public
/var/www/my-site
In PHP 7 and later, dirname($path, $levels) takes a second argument for how many levels to go up.
A project root constant
Define the root once, then build every path from it.
<?php
define("ROOT", dirname(__DIR__));
require ROOT . "/includes/functions.php";
$template = ROOT . "/templates/header.php";
Joining paths
Always use / in PHP, even on Windows. PHP understands it on both systems. DIRECTORY_SEPARATOR exists, but you rarely need it.
<?php
function path(string ...$parts): string
{
return preg_replace('#/+#', "/", implode("/", $parts));
}
echo path("/var/www/", "/uploads/", "photo.jpg");
/var/www/uploads/photo.jpg
Useful path functions
<?php
$file = "/uploads/2026/report.final.pdf";
echo basename($file) . "\n";
echo pathinfo($file, PATHINFO_EXTENSION) . "\n";
echo pathinfo($file, PATHINFO_FILENAME);
report.final.pdf
pdf
report.final
Check that the file exists
<?php
$file = __DIR__ . "/nothing-here.php";
var_dump(is_file($file));
bool(false)
Related constant: __FILE__
__FILE__ is the full path of the current file, including its name. __DIR__ is the same as dirname(__FILE__).
Habit
require and include with __DIR__ .. It removes a whole category of “works on my page, fails on yours” bugs.