[TIP] Always know the absolute path of your website


New member
It's very important to know your absolute path.

Imagine the situation where you are running a script main.php and in this script you have included another file foo/include.php AND, inside this file, you want to include another file bar/include-2.php, here you can think of two possibilities:

The included path is relative to foo/include.php
The included path is relative to main.php

As of the PHP Documentation the file included is ALWAYS relative to the script running (in that case, main.php). The include function only "copies" the contents of the included file. That means that if you want to use a relative path, you should know if you are being included and what file is including you.

There are some workarounds. Magic constants like __FILE__ and __DIR__ (as of php 5.3.0) may help you, but, if you need to move the including file, you will have some problem. Example:

Now you're using __DIR__ for including bar/include-2.php in foo/include.php, so your code looks like this:

// code code code

// this '../' looks dirty but we are not talking about it now
include __DIR__ . '/../bar/include-2.php';

// code code code

Everything is working as expected, but you are relocating your files and need to move foo/include.php to another folder, let's say foo/bar/include.php. Your code will stop working. Why?

__DIR__ will start pointing to /path/to/website/public_html/foo/bar and it will try to include the (probably nonexistent) file /path/to/website/public_html/foo/include-2.php. It is bad, isn't it? The solution is to change this code to look like this:

// code code code

// this '../../' looks double dirty but we are not talking about it now
include __DIR__ . '/../../bar/include-2.php';

// code code code

Well, it solved the problem. But now imagine that you have thousands of includes in your code, every with it's own directory and file. It would be very boring to fix all of them.

So, here comes the solution.
Have a file in your website root (usually public_html or another folder if you are hosting more than one website) named config.php (you choose the name, this is mine) and use this code inside of the file:

define('ABSOLUTE_PATH', dirname(__FILE__));

Done. Now just include this file one time inside your main script (or multiple scripts) and you are ready to go. The final foo/include.php code would look like this:

// ok '../', you win this time
include '../config.php';

// code code code

include ABSOLUTE_PATH . '/bar/include-2.php';

// code code code

This is much cleaner and easier to maintain. So, if you relocate foo/include.php you just have to change one line of code and all your includes are working again.
Also, if you move /bar/include-2.php you can use search and replace because all includes should be standardized.