Skip to content

PHP Tutorial Include and Require

File Paths and __DIR__

Lesson 161 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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.

index.php
PHP
<?php
echo basename(__DIR__) !== "" ? "__DIR__ is always set" : "";
Output
OUTPUT
__DIR__ is always set

Use it to build a path:

index.php
PHP
<?php
require __DIR__ . "/config.php";                 // same folder
require __DIR__ . "/../includes/functions.php";  // one folder up

Going up with dirname()

index.php
PHP
<?php
$path = "/var/www/my-site/public/index.php";

echo dirname($path) . "\n";
echo dirname($path, 2);
Output
OUTPUT
/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.

index.php
PHP
<?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.

index.php
PHP
<?php
function path(string ...$parts): string
{
    return preg_replace('#/+#', "/", implode("/", $parts));
}

echo path("/var/www/", "/uploads/", "photo.jpg");
Output
OUTPUT
/var/www/uploads/photo.jpg

Useful path functions

index.php
PHP
<?php
$file = "/uploads/2026/report.final.pdf";

echo basename($file) . "\n";
echo pathinfo($file, PATHINFO_EXTENSION) . "\n";
echo pathinfo($file, PATHINFO_FILENAME);
Output
OUTPUT
report.final.pdf
pdf
report.final

Check that the file exists

index.php
PHP
<?php
$file = __DIR__ . "/nothing-here.php";

var_dump(is_file($file));
Output
OUTPUT
bool(false)

__FILE__ is the full path of the current file, including its name. __DIR__ is the same as dirname(__FILE__).

lightbulb
Habit
Start every require and include with __DIR__ .. It removes a whole category of “works on my page, fails on yours” bugs.