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.