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]

 



On Mon, Jul 6, 2009 at 11:04, Govinda<govinda.webdnatalk@xxxxxxxxx> 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

-- 
</Daniel P. Brown>
daniel.brown@xxxxxxxxxxxx || danbrown@xxxxxxx
http://www.parasane.net/ || http://www.pilotpig.net/
Check out our great hosting and dedicated server deals at
http://twitter.com/pilotpig

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