note 36658 deleted from function.include by sniper
| From: | sniper@php.net | Date: | Tue, 04 Nov 2003 00:43:10 +0000 |
| Subject: | note 36658 deleted from function.include by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-59800@lists.php.net to get a copy of this message | ||
Note Submitter: srjosh@!nospam!.maestrakara.com
----
I noticed several solutions regarding different ways of addressing filepaths in includes -
particularly multi-tiered includes. However, none of them worked for me. Most of the ones I found
seem to rely on root-level addressing, which wasn't working for me. My server is set to not
accept variables from external pages, and it was reading the root addressed pages as external.
Anyway, here is what I came up with:
// Send this function a root-formatted address and it will calculate a relative address -
// i.e. $dest="/includes/format_include.php" will be translated to
"../../includes/format_include.php"
function new_address($dest){
//splits current directory into an array to be compared to target directory.
$current = explode ("/", $_SERVER["SCRIPT_NAME"]);
//splits target directory into an array to be compared to current directory.
$dest = explode ("/", $dest);
$relative_toggle=true;
for ($x=0;$x<count($dest);$x++){
debug($x);
if ($relative_toggle==true){
if ($dest[$x]==$current[$x]){
$toURL = $toURL . "../";
} else {
$relative_toggle = false;
}
} else {
if ($x == count($dest)-1) {
$toURL = $toURL . $dest[$x];
} else {
$toURL = $toURL . $dest[$x] . "/";
}
}
}
return ($toURL);
}
It works by splitting both current address (as reported by $_SERVER["SCRIPT_NAME"]) and
the target address as fed to the function into arrays based on the slashmarks, then running a
comparison.
Each array value correspondes to a directory, of course. It seemed counter-intuitive to me at
first, but if the target and current arrays MATCH, then the relative URL you are building needs a
"../" for that level. If they DON'T match, then you are at the point where the
target directory structure takes over. This is where the $relative_toggle comes into play.
Finally, do note that $_SERVER["SCRIPT_NAME"] doesn't report query strings, so if
that is important to you, you might need to change that part of the code.