Relative and Absolute Paths in PHP - Enhanced Guide
- Intro
- Difference between Absolute and Relative Paths
- Absolute Paths
- Relative Paths
- Document Root
- Web Server Paths
- Console Scripts
- Helpful PHP Commands and Constants
Intro
Websites exist in two worlds: the real (filesystem) and the virtual (web). Understanding this distinction is critical for PHP developers.
For example, in http://example.com/file.html, the browser does not see a physical fileβit only requests a virtual resource. Whether a file exists on disk is irrelevant to the browser.
Developers, however, work with the real files on disk. PHP scripts interact with these files when including scripts, reading data, or writing logs.
Difference between Absolute and Relative Paths
Paths can be classified as:
- Absolute: Start from the root of the filesystem or site.
- Relative: Start from the current working directory or location.
Analogy: A postal address "123 Main St" is absolute, while "Turn right two blocks" is relative.
Absolute Paths
Absolute paths always start from the root:
- Unix:
/var/www/site/index.php - Windows:
C:\Windows\system32\cmd.exe
Absolute paths are reliable: no matter where you start, the path points to the same file.
Relative Paths
Relative paths depend on the current working directory:
index.htmlβ same folder./file.phpβ current folderimages/pic.jpgβ subfolder../file.phpβ parent folder
// Current folder: /var/www/site/about
include '../config/settings.php';
// Resolves to /var/www/site/config/settings.php
Document Root
The DOCUMENT_ROOT is the filesystem folder that corresponds to the site root. Example:
/var/www/site/forum/index.php
http://example.com/forum/index.php
For PHP to access this file:
$file = $_SERVER['DOCUMENT_ROOT'] . '/forum/index.php';
Web Server Paths
For the browser, paths start from the site root:
- Absolute URL:
/job/vacancy.php - Relative URL:
vacancy.phpfrom /about/ folder resolves incorrectly
Console Scripts (Single Entry Point)
In CLI scripts, $_SERVER['DOCUMENT_ROOT'] is unavailable. Use __DIR__ to build paths:
$configPath = __DIR__ . '/../config/settings.php';
require $configPath;
define('ROOT_DIR', realpath(__DIR__ . '/../'));
include ROOT_DIR . '/config/settings.php';
Helpful PHP Commands and Constants
__FILE__β full path to the current file__DIR__β current folderrealpath()β converts relative path to absolutegetcwd()β current working directory
__DIR__ with realpath() for robust cross-platform scripts.