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
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)
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:
Then, just include files using their paths relative to the application root folder, for example:
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
../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