Govinda wrote:
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:


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) {
} else {
   // Handle the error for the incorrect inclusion attempt.


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:

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

versus this:

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

versus this:

   .... 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.

$documentRoot = '/srv/website/www'

Unless you change your site configuration option, that is both concise and easy to understand when you (or someone else) reads the code 5 months from now.

PHP General Mailing List (
To unsubscribe, visit:

Reply via email to