13

In php, if i have a file that requires a file from a subdirectory like:

require('directory/file.php');

and file.php wants to require another file in its own directory, is the path relative to file.php or the file that it is included in?

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
user2075470
  • 131
  • 1
  • 4

3 Answers3

8

It's relative to the original requiring file if that makes sense.

So, if you have a file called index which looks like this:

require("./resources/functions.inc.php");

And then functions.inc.php would need to look like this:

require("./resources/anotherFunctionsFile.inc.php");

Rather than:

require("anotherFunctionsFile.inc.php);

But really you should be making use of the __DIR__ constant, which is always the directory the script is being ran from; it makes things a lot easier.

More information about __DIR__ and other constants: http://php.net/manual/en/language.constants.predefined.php

I hope that helps.

EM-Creations
  • 4,195
  • 4
  • 40
  • 56
5

It's relative to the main script, in this case A.php. Remember that require() just inserts code into the currently running script.

That is, does it matter which file the require() is called from

No.

If you want to make it matter, and do an require() relative to B.php, use the __FILE__ constant (or __DIR__ since PHP 5.3) which will always point to the literal current file that that line if code is located in.

include(dirname(__FILE__)."/C.PHP");
Minesh
  • 2,284
  • 1
  • 14
  • 22
1
include(dirname(__FILE__).'/include.php');

REF : http://php.net/manual/en/language.constants.predefined.php

The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, FILE always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
  • 2
    in php 5.3 and up, you can use `__DIR__` instead of `dirname(__FILE__)`. (one should be using at least 5.3, since older versions are not supported) – SDC Feb 15 '13 at 12:35