Skip to content

Instantly share code, notes, and snippets.

Last active Aug 18, 2018
What would you like to do?
Why you should not use relative paths when working with files in PHP

TL;DR do what the last section tells you to do

What is the difference between a relative path and an absolute path?

An absolute path is one which includes all path components from the root of the file system. It starts with a leading / on unix-like operating systems, or a drive letter on Windows.

Unix: /full/path/to/file.php
Windows C:\full\path\to\file.php

A relative path is one which does not include all path components, but instead is a reference to the file based on the current working directory.


Why is using a relative path generally bad?

Relative paths rely on the current working directory. This is a form of global state, and as such it should be avoided whenever possible.

Depending on the structure of your application, the current working directory may not be guaranteed to be constant through all code paths that can reach a certain routine. It is also susceptible to change as a result of changes external to the code, such as a change in the way that URLs are interpreted by the web server by mechanisms such as URL rewriting. Relative paths can also be ambiguous in the context of static analysers, meaning that refactoring tools in IDEs can make mistakes and interpret the meaning of the path reference in unexpected ways.

What should you do instead of using a relative path?

It is often desirable to decouple your application from the true layout of the underlying file system, and reference a file with a relative path. In almost all cases, this means that you need to reference a path that is relative to the current source file, rather than the current working directory. This can be simply and unambiguously acheived using the __DIR__ constant that is built in to PHP. This constant always contains the full (absolute) path of the current source file, and thus can be used to construct an absolute path based on a relative path reference.

// don't do this...
include 'path/to/file.php';
// this instead:
include __DIR__ . '/path/to/file.php';
//                 ^
// You must include the additional leading slash in the path, the value of __DIR__ does not end with one
// It is always safe to use / as a path separator, this is completely portable to Windows

Using this technique will allow your code to reference relative resources and so remain decoupled from the underlying filesystem layout, while also being unambiguous and not dependent on the global state of the current working directory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment