Re: best way to properly build an include path *regardless* from where I am calling the include?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I want something that will work for calling an include from any file that
lives n levels deep.

   That's where you have to define a variable (or constant) that
tells the system where the web root is located, and then use that to
determine where you are in relation to that.  For example:

<?php

function relate_path($me,$root = '/home/pilotpig/public_html') {
   if(preg_match('/\/.*\.[a-z0-9]{2,5}$/Ui',$me)) { // If a file with
extension 2-5 alphanum chars
       $me = dirname($me); // Strip the filename

       // Then loop through the correct number of times.
for($i=0;$i<(substr_count($me,'/') - substr_count($root,'/')); $i++) {
           $me = dirname($me);
       }

       return $me; // Returns the resulting path.
   }

   return false; // If we were unable to get the path.
}

/*
   Then use it as follows, presuming this file is
   named /home/user/public_html/web/home.php
*/
if(($path = relate_path(__FILE__)) !== false) {
   include($path.'/include/config.php');
} else {
   // Handle the error for the incorrect inclusion attempt.
}
?>

   Voila!

Also, what is the difference between a path that starts with "/", versus the same path but that does not have that leading "/", or that same path but
prefixed with "./"?
I.e., this:
/somepath/includes/file.php

   .... is a true (absolute) path.

versus this:
somepath/includes/file.php

   .... is a relative path from wherever the file is called.

versus this:
./somepath/includes/file.php

   .... is a relative path from the CWD/PWD (Current Working
Directory/Present Working Directory).


   P.S. - The function is untested, just rattled off from my brain
while I cook dinner, so if it doesn't work, at least you should get
the gist of where I'm going.... but try it anyway.  ;-P

Dan I love to see smart hacks in action! ..and I believe I get what you are doing. I am just amazed that there is not a SIMPLE (one-liner) reliable way of just saying "document root" without a complex function like that. I mean what we need here is a global include path for the shared- hosted user .. an include_path that can be set for the virtual server user and it 'sticks' (does not have to be set on every page load). I think I'll let this all go for now... I have a lot of basics to cover before I trip out too much in any one area. I'm going to need the time and brain juice for some 'real' issues later ;-)
-G

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux