问题描述:

I'm brand new to php and I'm trying to work with some includes in my site and can't quite figure out how to make them all work correctly.

My site structure is as follows

/ROOT/

Config.php

Index.php

/ADMINISTRATION/

Index.php

mustInclude.php

/USERS/

Index.php

If "mustInclude.php" includes "Config.php" and Index.php includes "mustInclude.php" everything works fine, but as soon as I try to include "mustInclude.php" into /USERS/Index.php it breaks because "mustInclude.php" is using a path like include '../config.php'; and that isn't the same relative path for /USERS/Index.php as for /ADMINISTRATION/Index.php

I'm not really sure what to do here.

This is on my local machine for now. Using $_SERVER['DOCUMENT_ROOT'] gives me errors because it outputs my file structure (/Users/James/Sites) rather than my web structure (http://localhost/mysite)

Help?

网友答案:

IMO the best way to include files from anywhere in your application directory structure is to add the root folder of your app to your PHP include path:

<?php
set_include_path(get_include_path().PATH_SEPARATOR."/Users/James/Sites/app_name");

Then, just include files using their paths relative to the application root folder, for example:

<?php
require_once('ADMINISTRATION/USERS/Index.php');
网友答案:

I suggest defining some kind of "global base path" and deducing the other paths from there. Like,

define('BASE_PATH', '/home/me/');
...
include(BASE_PATH . 'Config.php');
include(BASE_PATH . 'subdirectory/other.php');

and so on. This kind of (semi)absolute paths are less fragile than relative paths containing lots of ../s. (Not to say that there's anything fundamentally wrong with relative paths, but they're harder to get just right and tend to break more easily. If /a includes b/c and b/c includes ../d/e, is that relative to /b/ or relative to /, or does it depend on whether we started from /a vs. called b/c directly? I don't even know. Better just use the absolute paths, they're easy and unambiguous :-).

网友答案:

Instead of using '../config.php' try using

dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'config.php'

This way you will always know that one level above is one level above from the current file.

网友答案:

you can use __FILE__

相关阅读:
Top