Tuesday, August 26, 2008

Beware of Relative Includes

Say you have an application with an index.php that contains:
require_once 'include/config.php';
require_once '/path_to_lib/util/all.php';
The util library also has an include/config.php file. In util/all.php it has:
require_once 'include/config.php';
Which config file will util/all.php include? Relative paths are converted to absolute pathnames with something like:
function relativeToAbsolute($relativePath) {
    return realpath(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $relativePath);
Since index.php is the script that is being executed then util/all.php will include the config file in the application folder instead of the one from the util library folder. The solution is instead of relative includes use:
require_once dirname(__FILE__) . '/include/config.php';


Post a Comment

Subscribe to Post Comments [Atom]

<< Home