note 97761 deleted from function.include by danbrown
| From: | danbrown@php.net | Date: | Thu, 06 May 2010 16:47:57 +0000 |
| Subject: | note 97761 deleted from function.include by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-169027@lists.php.net to get a copy of this message | ||
Note Submitter: aaronmann.co.cc
----
Here is the method I use to determine the pathing difference between the directory I'm
currently working in and the directory I want to collect an include file from. Keep in mind that
this is not good practice for common file names such as "index.php" and you will want to
be cautious. If misused, this routine could include a different file than the one you were
expecting.
<?php
//- usually I define all this in some prepend file that i always run first
//- we can create some array to store path or file information
//- I might use such an array to pre-define multiple include paths
$Path = array(
'dir' => 'some/deep/path/from/root/' ,
'file' => 'some_file_name.php' ,
'max' => 10 ,
); //- max will ^ limit how many times we can hop up
//- * you may also just want to combine the 'dir' and 'file' into one var.
//- notice how I did not define "up" into the $Path array
//- this is because it needs to be dynamic (only changed when needed),
//- so first we see if it's already set, if not, we set it blank
if( !isset($Path['up']) or strlen($Path['up']) < 1 ) $Path['up'] =
'';
//- we could combine our dir and file strings
$Path['inc'] = $Path['dir'] . $Path['file'];
//- then, we start by looking for the file in the current directory (while loop)
//- if it's not found we continue moving up until we find it or reach our limit
if( !file_exists($Path['up'] . $Path['inc']) ) {
while( !file_exists($Path['up'] . $Path['inc']) ) {
//- notice the concatenation .= we are extending the variable each loop
$Path['up'] .= "../";
//- we check our limit and stop if it's reached
if( strlen($Path['up']) / 3 >= $Path['max'] ) break;
}
} else { //- otherwise we found the file and can include it
include($Path['up'] . $Path['inc']);
}
//- once it locates the file, our $Path['up'] variable
//- is now updated to include anything from that directory
//- now we can include our file (and check for failure)
//- note that I use the error suppression @ symbol
//- to handle a failure gracefully using my own message
//- just in case it still didn't find the file
if( !@include($Path['up'] . $Path['inc']) ) {
exit('Failed to include file, program must now exit.');
}
?>