D. Alvarado <la***********@zipmail.com> wrote or quoted:
I have these files
/include/db_info.inc
/html_root/util_fns.inc
/html_root/home_page.php
/html_root/admin/admin_home.php
The page "util_fns.inc" contains the line
<?php include("../db_info.inc"); ?>
The page home_page.php contains
<?php include("util_fns.php"); ?>
and admin_home.php contains
<?php include("../util_fns.php"); ?>
but when I visit admin_home, I get the error
"main(../include/db_info.inc): failed to open stream: No such file or
directory". If I change the line in "util_fns.inc" to:
<?php include("../../db_info.inc"); ?>
the admin_home.php works fine, but the home_page.php page breaks. How
can I write the include line in "util_fns.inc" to accommodate both
situations?
The best solution I have found so far is the following code:
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);
}
Stick it into a library file which you /can/ include - and then
you can use:
"include_once_relative" in place of "include_once" - and it takes
account of a range of situations - including dealing with the
problem of the case where the path being specified is relative
to another included file - rather than the page being displayed.
Any improvements welcomed.
--
__________
|im |yler
http://timtyler.org/ ti*@tt1lock.org Remove lock to reply.