How do I format a PHP include() absolute (rather than relative) path?

前端 未结 9 914
情书的邮戳
情书的邮戳 2020-12-06 04:48

On various pages throughout my PHP web site and in various nested directories I want to include a specific file at a path relative to the root.

What single command c

相关标签:
9条回答
  • 2020-12-06 04:59

    You can just use include $_SERVER['DOCUMENT_ROOT'] . "/includes/analytics.php";

    0 讨论(0)
  • 2020-12-06 05:04

    As @Stefan Mai says, PHP doesn't have a "root" path but you can define one quite easily - most sites have a page that's included every time (e.g. configuration file), to which you can add:

    define('ROOT', dirname(__FILE__));
    

    Then use include ROOT . '/includes/analytics.php';

    Something that's also quite useful is the auto_prepend directive, which you can use in .htaccess on apache - not sure about setting it up on IIS (although you can have a global one in the PHP ini).

    0 讨论(0)
  • 2020-12-06 05:06

    The tilde is interpreted as a special character by the shell, so using it inside PHP code won't work regardless of OS.

    If you're trying to access something relative to a user home directory you could try getenv() - I'm pretty sure Windows sets an environment variable equivalent to $HOME.

    0 讨论(0)
  • 2020-12-06 05:06

    The way I found is:

    <?php include $_SERVER['DOCUMENT_ROOT'].'\\Your\\Site\\Path.php' ?>
    

    The \\ is necesary when you have some special character that could be escaped (i.e. \n), so that \\ is \ on the string.

    Because you are in windows, you have to use \ instead of /

    0 讨论(0)
  • 2020-12-06 05:07

    Use .. to go up a directory. So in pageone.php

    include 'includes/analytics.php';
    

    in pagetwo.php

    include '../includes/analytics.php';
    

    There's no notion of "root" as you're referring to in PHP as far as I know, though you could define it if you wanted. Best of luck!

    0 讨论(0)
  • 2020-12-06 05:14

    From the perspective of PHP root is the top of the file system on the web server, not the root from the perspective of the web browser.

    Most people do one of the below.

    Define a constant, in a global configuration file, and use that in each call to require/include.

    Or they use code like this.

    require_once realpath(dirname(__FILE__).'/config.php');
    require_once realpath(dirname(__FILE__).'/lib/Database.php');
    

    Using the environmental variables may be dangerous in some cases and be the source of security issues.

    0 讨论(0)
提交回复
热议问题