Tim Tyler <ti*@tt1lock.org> wrote or quoted:
I, Tim Tyler <ti*@tt1lock.org> wrote or quoted:
``If you use a relative path for include or include_one, the path is
relative to the running script, ie. the script that started all the
includes. There’s no easy way to include files relative to the current
file. This is a real hassle if you’ve got a library file that links to a
whole lot of other files. You can use absolute paths (with
$DOCUMENT_ROOT) but this is (obviously) less flexible.
I’ve finally figured out a solution, using _FILE_, realpath, and basedir:
include_once(realpath(dirname(__FILE__) . "../relative/path/to/file"))''
- http://www.ineffable.co.nz/archives/cat_php.html
So I reckon something like:
function include_once_relative($path) {
include_once(realpath(dirname(__FILE__)."../".$path));
}
...should patch things up - until the PHP designers fix up the problem.
That fails miserably on Windows running off a local webserver.
include_once("C:\Documents\HTML\~TimTyler\php\test \i.inc.php");
...isn't valid - you see.
As it stands, this solution is not acceptable - since it doesn't work.
Here is something that /does/ appear to work - at least in *my*
development and deployment environments, on *my* test data:
// test code...
include_once_relative("test.inc.php");
function include_once_relative($path) {
$from = realpath(dirname($_SERVER["SCRIPT_FILENAME"]));
$to = realpath(dirname(__FILE__)."/".$path);
include_once(relative_path($to,$from));
}
function relative_path ($targetfile, $basedir = '.') {
$basedir = realpath ($basedir);
$targetfile = realpath ($targetfile);
// on windows, check that both paths are on the same drive
if (substr ($basedir, 0, 1) != substr ($targetfile, 0, 1)) {
return false;
}
// split each path into its directories
$base_parts = split ('\/', str_replace ('\\', '/', $basedir));
$target_parts = split ('\/', str_replace ('\\', '/', $targetfile));
// ensure that there are no empty elements at the end (c:\ would cause it)
for ($i = count($base_parts) - 1; $i >= 0; $i--) {
if ($base_parts[$i] == '') {
unset ($base_parts[$i]);
} else {
break;
}
}
for ($i = count($target_parts) - 1; $i >= 0; $i--) {
if ($target_parts[$i] == '') {
unset ($target_parts[$i]);
} else {
break;
}
}
// get rid of the common directories at the beginning of the paths
$common_count = 0;
for ($i = 0; $i < count($base_parts); $i++) {
if ($target_parts[$i] == $base_parts[$i]) {
$common_count++;
} else {
break;
}
}
for ($i = 0; $i < $common_count; $i++) {
unset ($base_parts[$i]);
unset ($target_parts[$i]);
}
// build the resulting string
$cnt = count($base_parts) - 1;
if ($cnt < 1) {
$cnt = 0;
}
return str_repeat ('../', $cnt).implode('/', $target_parts);
}
Of course, this is now A Dreadful Hack :-|
--
__________
|im |yler
http://timtyler.org/ ti*@tt1lock.org Remove lock to reply.