On Jul 6, 2009, at 9:24 AM, Daniel Brown wrote:
On Mon, Jul 6, 2009 at 11:04, Govinda<govinda.webdnat...@gmail.com>
wrote:
Kim, this is exactly what I was looking for. I had been over
$_SERVER in
the docs.. but somehow missed that basic obvious param. Thanks!
And now I'll throw a monkey wrench into the gears and tell you
that, yes, it works, but don't always rely on it. The path translated
to/from the web server may not be the real path. And while you could
do your translation with realpath(), instead you should look into:
<?php include(dirname(dirname(__FILE__)).'/include/
file.php'); ?>
The example above uses the always-on reserved constant __FILE__
for the file in which it's written, regardless of how it's accessed
(as an include, etc.). So consider the following:
/home/user/public_html/index.php
/home/user/public_html/web/home.php
/home/user/public_html/templates/body.tpl.php
/home/user/public_html/include/file.php
In the example above, imagine that you access 'index.php', which
includes 'home.php', which - in turn - includes 'body.tpl.php' and
'file.php'. Using $_SERVER data will use the information given to it
by the webserver at the point of the call: in this case, from
/home/user/public_html/index.php. As such, the include path will be
relative to that. So if you're including a file in ./web/home.php,
you will need to hard-code the adjustment to account for the
difference.
Conversely, using the code example from above (and building upon
it), we know that __FILE__ remains static regardless of the point of
the call. Thus, it's a better and more reliable method, and is usable
even if $_SERVER data is not available to the script.
With this in mind, it should be quite simple to understand how the
following should work:
<?php
// My Name: /home/user/public_html/web/home.php
$file_to_include = dirname(dirname(__FILE__)).'/include/file.php';
if(file_exists($file_to_include) && is_readable($file_to_include)) {
include($file_to_include);
} else {
// Do your error handling here.
}
?>
.... but to each his/her own! ;-P
Michael and Dan
this is great, but then I still do not have a solution that will work
for any level deep of dir/ .
I.e. this-
dirname(dirname(__FILE__))
gives the correct first part of the path to document root like
$_SERVER['DOCUMENT_ROOT'] does
only when called from a file that is 2 levels deep.
I want something that will work for calling an include from any file
that lives n levels deep.
Isn't there anything reliable that effectively says, "from document
root"??
I do not really understand why
$_SERVER['DOCUMENT_ROOT']
should return the right data at one time and not at another. (?)
--
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
versus this:
somepath/includes/file.php
versus this:
./somepath/includes/file.php
("../" I know)
-G