Forum Moderators: coopster
e.g.
-------------------------------------------------------
include($_SERVER['PHP_SELF'] . '/path/to/file.php');
echo $variableInFile; // Variable not found
-------------------------------------------------------
Is there any way to include a file with an absolute path and still have the variables visible globally (some workaround using sessions is overkill).
Also the example you give doesn't look right to me, usually $_SERVER['PHP_SELF'] points to a file but you're using it as a directory name in your include statement. Perhaps you meant $_SERVER['DOCUMENT_ROOT'].
OK, I just realised why absolute paths are probably affecting the variable scope. I am being a bit stupid here. I will explain: I'm actually trying to use a function that allows me to specify absolute paths for includes.
----------------------------------------------------------------------------------------------
// http://www.example.com/includes/config.phpdefine('DOC_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/');
define('ROOT', 'http://www.example.com/');
define('ORDER', ROOT . 'order/');
// http://www.example.com/includes/functions.php
function abs_include($path, $once = false) {
$path = str_replace(ROOT, DOC_ROOT, $path);
if ($once) {
include_once($path);
} else {
include($path);
}
}
// http://www.example.com/order/file.php
$myVar = 'Hello';
//************** USAGE
abs_include(ORDER . 'file.php');
echo $myVar; // Not found
----------------------------------------------------------------------------------------------
To explain briefly, config.php is always included with every page, and contains some constants which link to important directories. The reason for the abs_include() function is that I want to be able to use those constants when specifying includes, but I have to use $_SERVER['DOCUMENT_ROOT'] in an include() otherwise it won't find the file correctly. So the function allows me to specify a standard absolute URI to include, such as 'http://www.example.com/order/file.php'
function get_abs_include_path($path) {
$path = str_replace(ROOT, DOC_ROOT, $path);
return $path;
}
...
include get_abs_include_path(ORDER . 'file.php');