Presuming there is no client-side code being run in doAllTheThings.php
and you know the path to doAllTheThings.php
.
The main issue is how include
resolves paths within nested include
files.
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. [sic]
In this case the calling script is customInterface.php
.
Being that include
resolves relative paths from the current working directory of the executed script file, the simplest approach to circumvent the issue and make the calling script behave as if you executed doAllTheThings.php
directly, you can use chdir
in order to change the current working directory.
<?php
//...
if (true) {
//check to make sure doAllTheThings.php actually exists and retrieve the absolute path
if (!$doAllThings = realpath('../../things/important/doAllTheThings.php')) {
throw new \RuntimeException('Unable to find do all things');
}
//change working directory to the same as doAllTheThings.php
chdir(dirname($doAllThings));
//include doAllTheThings from the new current working directory
include $doAllThings;
//change the working directory back to this file's directory
chdir(__DIR__);
}
//...
?>
include __DIR__
or dirname(__FILE__)
However, if possible, I strongly recommend using absolute paths by including the root path, by appending __DIR__
or dirname(__FILE__)
in PHP < 5.3 to any relative include
paths. This will absolve the need to use chdir()
as a workaround, and allow PHP to resolve the correct paths to include, while also allowing the application as a whole to function on any system the scripts are executed from.
<?php
include __DIR__ . '/../importantThing1.php';
include __DIR__ . '/../importantThing2.php';
include __DIR__ . '/../importantThing3.php';
set_include_path
Another more complex approach is to specify the include file directories, by using set_include_path()
. However, if you are not aware of the directory the nested include scripts are in, this would require you to parse the include file to check for them. As such I do not recommend this approach, albeit viable.
<?php
if ($doAllThings = realpath('../../things/important/doAllTheThings.php') {
//retrieve the directory names of the scripts to be included
$basePath = dirname($doAllThings);
$subPath = dirname($basePath);
//add the directories to the include path
$include_path = set_include_path(get_include_path() . PATH_SEPARATOR . $basePath . PATH_SEPARATOR . $subPath);
include $doAllThings;
//restore the include path
set_include_path($include_path);
}