Chris Muench
Chris Muench

Reputation: 18318

Relative include files

I have a file

workers/activity/bulk_action.php which includes a file

include('../../classes/aclass.php');

Inside aclass.php it does:

include ('../tcpdf/config/lang/eng.php');

It seems that the include in the second file is using the first files working directory instead of being relative to itself, resulting in an error. How does this work?

Upvotes: 1

Views: 1397

Answers (3)

Czechnology
Czechnology

Reputation: 14992

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.

You can use dirname(__FILE__) to get a path to the directory where the currently executed script resides:

include(dirname(dirname(__FILE__)) . '/tcpdf/config/lang/eng.php');

(since PHP 5.3, you can use __DIR__)

Or, define a constant in the first file that points to the root directory and use it in your includes.

Upvotes: 0

Philippe Gerber
Philippe Gerber

Reputation: 17836

You would be way better off by setting a proper value to the include_path and then use paths relative to this directory.

set_include_path(
    get_include_path() .
    PATH_SEPARATOR .
    realpath(__DIR__ . '/your/lib')
);

include 'tcpdf/config/lang/eng.php';
include 'classes/aclass.php';

I also suggest you take a look at autoloading. This will make file includes obsolete.

Upvotes: 1

mario
mario

Reputation: 145482

You can adapt the second include with:

include (__DIR__.'/../tcpdf/config/lang/eng.php');

The magic constant __DIR__ refers to the current .php file, and by appending the relative path after that, will lead to the correct location.

But it only works since PHP5.3 and you would have to use the dirname(__FILE__) construct instead if you need compatibility to older setups.

Upvotes: 13

Related Questions