0

I have three files at my server:

foo.php
assets/bar.php
assets/qux.php

foo.php includes bar.php, and bar.php includes qux.php. The code of foo.php is shown below:

<?php
    include_once("assets/bar.php");
?>

How should bar.php include qux.php? Should it use include("qux.php") or include("assets/qux.php")?

FalconC
  • 1,303
  • 2
  • 13
  • 22
  • includes get interpreted in the scope they are called in. – Orangepill Jul 30 '13 at 15:45
  • 1
    Have you tried it? Which one worked? – JJJ Jul 30 '13 at 15:46
  • Asking is one way of getting the answer, but trying some experimenting (add some echo statements and what not) would likely be a better learning experience. – ernie Jul 30 '13 at 15:46
  • You should use `include (__DIR__."/qux.php");` – Orangepill Jul 30 '13 at 15:47
  • 1
    @Gordon The "duplicate" doesn't talk about the paths at all. – JJJ Jul 30 '13 at 15:51
  • It's pretty much explained in the PHP Manual: 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. 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. See http://php.net/manual/en/function.include.php – Gordon Jul 30 '13 at 15:52
  • @Juhana I have tried both, but they both don't work. I wanted to be sure I was using the right one before I spend my time at (unnecessary) debugging. – FalconC Jul 30 '13 at 15:54
  • @Juhana it's good enough for me since it references the PHP manual which the OP doesn't mention at all to have consulted prior to asking. But anyway, I'll reopen it. – Gordon Jul 30 '13 at 15:56

3 Answers3

2

If they are in the same directory, then it is simply:

include("qux.php")
Paddyd
  • 1,850
  • 15
  • 25
2

Assuming you haven't modified your includes path, include_once('qux.php') should work fine.

ponysmith
  • 427
  • 2
  • 4
0

It actually should use include("assets/qux.php"). The path to included files is dynamic; it depends in this case on foo.php.

If you are going to include bar.php from multiple directories, it is probably better to use absolute paths.

So, there are two ways to "chain-include" files in PHP:

Way #1 (Dynamic relative path)

include("assets/qux.php");

Way #2 (Absolute path)

$ROOT = realpath($_SERVER["DOCUMENT_ROOT"]);
include("$ROOT/assets/qux.php");

As seen here

Community
  • 1
  • 1
FalconC
  • 1,303
  • 2
  • 13
  • 22