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

From: Date: Tue, 07 Jul 2009 06:27:18 +0000
Subject: Re: best way to properly build an include path *regardless* from where I am calling the include?
References: 1 2 3 4 5 6 7  Groups: php.general 
Request: Send a blank email to php-general+get-294988@lists.php.net to get a copy of this message
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: <?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.
$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.

« previous php.general (#294988) next »