Lukas
Lukas

Reputation: 169

Include relative path works strangely

I have this folder and file structure:

In index.php I call:

require_once("../resources/render_template.php");

In render_template.php I call:

require_once("configs/main_config.php");

Or: (both work)

require_once("../resources/configs/main_config.php");

My questions:

  1. Why does the require_once("configs/main_config.php") work? Shouldn't the path now need to be relative to the index.php because the render_template.php file is included in the index.php which means need to add ../resources/ to leave the public_html folder?

  2. If the first way is correct, why does require_once("../resources/configs/main_config.php"); then work?

Upvotes: 1

Views: 33

Answers (1)

El_Vanja
El_Vanja

Reputation: 3983

The way it works is anything but strange. It follows a logical pattern.

  1. Why does the require_once("configs/main_config.php") work?

It works because it doesn't asses the relative path based on where this "parent" file is included. main_config.php is included in render_template.php. It does not need to know where render_template.php might be included.

If it actually depended on where the parent file is included, then you would need to define the relative path differently for files from different folders, which obviously cannot work. It has to be universal so the script could be included wherever it's needed.

It is achieved by first including the files at the "lowest" level. index.php includes render_template.php which includes main_config.php. This means that before render_template.php contents are added to index.php, main_config.php contents will be added to render_template.php. So they will ultimately together be added to index.php at the place where require_once("../resources/render_template.php") is called.

  1. If the first way is correct, why does require_once("../resources/configs/main_config.php"); then work?

No reason for it not to work. If you take what we've stated in the first answer (that it is independent of where the "parent" is included), it follows an exact path:

  • We are currently inside the resources folder, in render_template.php.
  • We move one level above (..) into the "root" folder (that contains both public_index and resources folders).
  • We move back into the resources folder. The rest is straightforward.

Upvotes: 1

Related Questions