Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php include path changing based on file

Tags:

include

php

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?

like image 241
James P. Wright Avatar asked Nov 21 '25 02:11

James P. Wright


2 Answers

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 :-).

like image 100
Joonas Pulakka Avatar answered Nov 22 '25 15:11

Joonas Pulakka


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');
like image 32
Ben James Avatar answered Nov 22 '25 16:11

Ben James