How does include path resolution work in require_once? How does include path resolution work in require_once? php php

How does include path resolution work in require_once?


If you include another file, the working directory remains where the including file is.

Your examples are working as intended.

Edit: The second example works because . (actual directory) is in your include path (see your error message).

Edit2:In your second example, the key point of your interest is this line:

<?php require_once("f2.php"); ?>

At first it will look in the current working dir (/var/www/req_path_test), but does not find f2.php.

As fallback, it will try to find f2.php in your include_path ('.:/usr/share/php:/usr/share/pear'), starting with '.' (which is relative to the actual file, not the including one).

So './f2.php' works and the require does not fail.


When you open index.php, working dir is set to the folder this file resides in. And inside insluded f1.php this working dir does not change.

You can include files by using their absolute paths, relative to the current included file like this:

require_once(dirname(__FILE__).'/../../test/file.php')

But better consider using an autoloader if these files contain classes.


Normaly in you old structure

<?php require_once("f2/f2.php"); ?>

instead of

<?php require_once("../f2/f2.php"); ?>

should work. As far as i know php takes the paths from the initial script