Search code examples
phpinclude-path

Paths confusion: relative / absolute / relative to DOCUMENT_ROOT?


I have just started learning PHP and I have read several answers to pretty much similar question, but it didn't help.

I have several files:

index.php 
folder1\file.php
folder2\file.php 

So index.php includes folder1\file.php and it is really easy. Then folder1\file.php includes folder2\file.php. The book I am reading says to do this I have to write this inside folder1\file.php:

require $_SERVER['DOCUMENT_ROOT'] . '/' . 'folder2/file.php';

So basically why didn't they do this?

require 'folder2/file.php';

As far as I understood, all the paths are always relative to the initial script's location and it works just fine on my machine.

I still don't get why not use .\folder\file.php which would keep it working if I move my directory deeper or copy the whole website to another machine.

According to the manual: If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory.


Solution

  • The PHP manual says:

    Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing.

    So it's always a best practice to set the include path in your master file (in your case, index.php) using the set_include_path() method.

    When working with frameworks or customised servers, it is good to specify your include path without leaving behind the system defined include paths by doing the following:

    set_include_path(get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT']);
    

    That way, your new include path will be added to the existing paths.

    For what you have asked in the question, it is always better to specify the include path as I mentioned above and then refer your files relatively. If in case in future you want to move your files, editing just one line will do instead of finding and replacing in hundreds of files.

    Example:

    index.php:

    set_include_path(get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT']);
    require('folder1/file.php');
    

    folder1/file.php:

    require('folder2/file.php');
    

    folder2/file.php:

    require('folder3/file.php');
    

    and so on..