Absolute & Relative Paths In PHP – A Simple Guide

Welcome to a quick tutorial on absolute and relative paths in PHP. So you have set a verified file path, but PHP is still complaining about “missing” files and folders? Yes, it is easy to get lost with absolute and relative paths in PHP.

  • An absolute path refers to defining the full exact file path, for example, D:\http\project\lib\file.php.
  • While a relative path is based on the current working directory, where the script is located. For example, when we require "html/top.html" in D:\http\page.php, it will resolve to D:\http\html\top.html.

The covers the basics, but let us walk through more on how file paths work in PHP – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes PHP File Path Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

PHP FILE PATH

All right, let us now get into the examples of how file paths work in PHP.

 

1) ABSOLUTE & RELATIVE PATH

D:\http\1a-dummy.php
<?php
echo "Foo Bar";
D:\http\1b-abs-rel.php
// (A) ABSOLUTE FILE PATH (FULL PATH)
require 'D:\http\1a-dummy.php';
 
// (B) RELATIVE PATH (TO CURRENT WORKING DIRECTORY)
require '1a-dummy.php';

As in the introduction above:

  • An absolute file path is simply the “full file path”. Although a bit long-winded, it’s hard to mess up with this one.
  • On the other hand, the relative file path is based on the current working directory.

But just what the heck is the “current working directory”? Follow up with the next example.

 

2) CURRENT WORKING DIRECTORY

D:\http\2-cwd.php
<?php
// IF THIS SCRIPT IS PLACED IN D:\HTTP
// CURRENT WORKING DIRECTORY WILL BE D:\HTTP
echo getcwd();

In simple terms, the current working directory is the folder where the currently executing script is placed in. We can easily get the current working directory with the getcwd() function.

 

 

3) THE CONFUSION WITH CURRENT WORKING DIRECTORY

D:\http\inside\3-script.php
<?php
require 'D:\http\2-cwd.php';

So far so good with relative paths? Now comes the part that destroyed many beginners, take extra note that this example script is placed at D:\http\inside. Guess what getcwd() will show when we run this example?

Yes, the current working directory now changes to D:\http\inside. That is what I meant by “the current working directory is the folder where the currently executing script is at”.

 

4) CHANGING THE WORKING DIRECTORY

D:\http\inside\4-change-cwd.php
<?php
// (A) SHOW CURRENT WORKING DIRECTORY
// D:\HTTP\INSIDE
require 'D:\http\2-cwd.php';
 
// (B) CHANGE TO PARENT FOLDER
// D:\HTTP
chdir("../");
echo getcwd();

The current working directory will surely mess up a lot of relative paths. So, how do we fix this problem? Thankfully, we can use the chdir() function to change the current working directory.

 

 

5) MAGIC CONSTANTS

D:\http\5-magic.php
<?php
// (A) CURRENT FILE - D:\HTTP\5-MAGIC.PHP
echo __FILE__ . "<br>";
 
// (B) CURRENT FOLDER - D:\HTTP
echo __DIR__ . "<br>";

Even if we are able to change the working directory, relative paths are still messy in big projects. I will recommend using magic constants instead.

  • __FILE__ is the full path and file name where the current script is located.
  • __DIR__ is the folder where the current script is located.

 

6) MAGIC CONSTANTS VS WORKING DIRECTORY

D:\http\inside\6-magic.php
<?php
// (A) CURRENT FILE - D:\HTTP\INSIDE\6-MAGIC.PHP
echo __FILE__ . "<br>";
 
// (B) CURRENT FOLDER - D:\HTTP\INSIDE
echo __DIR__ . "<br>";
 
// (C) GET PARENT FOLDER
$parent = dirname(__DIR__) . DIRECTORY_SEPARATOR;
require $parent . "5-magic.php";

To lessen the confusion, take note that the magic constants are different from the current working directory.

  • The current working directory is based on the first script that we run.
  • Magic constants are based on where the scripts are placed in.

Yes, magic constants are the better way to do “pathfinding”, and to build the absolute paths.

 

 

7) MORE PATH YOGA

D:\http\7-extra.php
<?php
// (A) SERVER PATH VARIABLES
echo $_SERVER["DOCUMENT_ROOT"] . "<br>"; // D:/HTTP
echo $_SERVER["PHP_SELF"] . "<br>"; // 7-EXTRA.PHP
echo $_SERVER["SCRIPT_FILENAME"] . "<br>"; // D:/HTTP/7-EXTRA.PHP
 
// (B) PATH INFO
$parts = pathinfo('D:\http\inside\index.php');
echo $parts['dirname'] . "<br>"; // D:\HTTP\TEST\INSIDE
echo $parts['basename'] . "<br>"; // INDEX.PHP
echo $parts['filename'] . "<br>"; // INDEX
echo $parts['extension'] . "<br>"; // PHP
 
// (C) BASENAME
$path = 'D:\http\inside';
echo basename($path) . "<br>"; // INSIDE
$path = 'D:\http\inside\foo.php';
echo basename($path) . "<br>"; // FOO.PHP
$path = 'D:\http\inside\foo.php';
echo basename($path, ".php") . "<br>"; // FOO
 
// (D) DIRNAME
$path = 'D:\\http\\inside\\';
echo dirname($path) . "<br>"; // D:\HTTP
echo dirname($path, 2) . "<br>"; // D:\
 
// (E) REALPATH
echo realpath("") . "<br>"; // D:\HTTP
echo realpath("../") . "<br>"; // D:\

Finally, this is a quick crash course on the various variables and functions that may help you find the file path.

SERVER SUPERGLOBAL

  • $_SERVER["DOCUMENT_ROOT"] – Contains the root HTTP folder.
  • $_SERVER["PHP_SELF"] – The relative path to the script.
  • $_SERVER["SCRIPT_FILENAME"] – The full path to the script.

PATH INFO

The PHP pathinfo() function will give you bearings on a given path:

  • dirname – The directory of the given path.
  • basename  – The filename with extension.
  • filename – Filename, without extension.
  • extension – File extension.

BASENAME

The basename() function will give you the trailing directory or file of a given path.

DIRNAME

The dirname() function will give you the parent directory of a given path.

REALPATH

The realpath() function gives you a canonicalized absolute path… Kind of useful, but still based on the current working directory.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

EXTRA) FORWARD OR BACKWARD SLASH?

In case you have not realized:

  • Windows use \
  • Linux and Mac uses /

Not really a big problem though, just use DIRECTORY_SEPARATOR in PHP and it will automatically resolve to the “correct slash”.

 

ALL THE PATH-RELATED VARIABLES

Variable Description
__FILE__ The absolute path and file name of the current script.
__DIR__ The absolute path of the current script.
$_SERVER["DOCUMENT_ROOT"] The root HTTP folder.
$_SERVER["PHP_SELF"] Relative path to the script.
$_SERVER["SCRIPT_FILENAME"] Full path (and filename) to the script.
DIRECTORY_SEPARATOR This is automatically a forward or backward slash, depending on the system.

 

ALL THE PATH-RELATED FUNCTIONS

Function Description
getcwd() Returns the current working directory.
chdir() Changes the current working directory.
pathinfo() Gives you the path information of a given path.

  • dirname – The directory of the given path.
  • basename – The filename with extension.
  • filename – Filename, without extension.
  • extension – File extension.
basename() Get the trailing directory or file of a given path.
dirname() Get the parent directory of a given path.
realpath() Canonicalized absolute path.

 

LINKS & REFERENCES

 

INFOGRAPHICS CHEAT SHEET

Absolute Relative Path In PHP (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope it has helped you find the true path, and if you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Absolute & Relative Paths In PHP – A Simple Guide”

  1. You wrote “Windows uses \ and Linux uses /”
    Not exactly… Only Windows is using \ and everyone else use /
    It came from their first DOS, which did not have a directory/folder system, and after a while when they updated their DOS they were not able to put the standard / as their customers using their DOS had already used the / for something else, so Microsoft adopted the backslash as an alternative as it was recognizable to the /

    1. Eh… Thank you for rephrasing “Windows uses \ and Linux uses /” to “Only Windows is using \ and everyone else use /”?

      Sorry, I am just very confused about what you are trying to share here. Maybe a piece of history to why Mircosoft is the odd one out? If that is so, then… Thank you for the history lesson??

Leave a Comment

Your email address will not be published. Required fields are marked *