Relative and Absolute Paths in PHP - Enhanced Guide

  1. Intro
  2. Difference between Absolute and Relative Paths
  3. Absolute Paths
  4. Relative Paths
  5. Document Root
  6. Web Server Paths
  7. Console Scripts
  8. 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.

πŸ’‘ Beginner Tip: The browser works virtually; PHP works physically. Confusion between the two causes most path-related errors.

Difference between Absolute and Relative Paths

Paths can be classified as:

Absolute path (Unix): /var/www/site/index.php Relative path (Unix): ./index.php or ../index.php

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 filesystem: / (root) /var/ /var/www/ /var/www/site/index.php Windows filesystem: C:\ C:\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:

πŸ’‘ Tip: PHP and web servers internally convert relative paths to absolute paths. Always know your current directory!
// 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';
Browser sees: http://example.com/forum/index.php PHP sees: Filesystem path: /var/www/site/forum/index.php

Web Server Paths

For the browser, paths start from the site root:

πŸ’‘ Tip: Always use site-root absolute paths for internal links, scripts, and images.

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;
πŸ’‘ Best practice: Define a ROOT_DIR constant in a bootstrap file for all scripts.
define('ROOT_DIR', realpath(__DIR__ . '/../'));
include ROOT_DIR . '/config/settings.php';

Helpful PHP Commands and Constants

πŸ’‘ Mid-level tip: Combine __DIR__ with realpath() for robust cross-platform scripts.