嵌套include_once问题

Here is my directory tree:

  • /
    • index.php
  • include/
    • functions.php
    • head.php
    • connect.php
  • sub/
    • index.php

In my head.php and connect.php both have:

include_once 'include/functions.php';

My index.php in the root folder includes these two: head.php and connect.php like this:

include_once 'include/connect.php';
include_once 'include/head.php;'

However, when my index.php in sub/ includes functions.php and head.php, they would fail to also include functions.php. Here's how I included in the sub/index.php:

include_once '../include/connect.php';
include_once '../include/head.php';

If I change in the head.php and connect.php to: include_once '../include/functions.php';

The sub/index.php would include everything normally but the index.php in the root would fail to load the functions.php.

How can I fix this?

PHP version: 5.2.*


The Error


Include statement error in head.php and connect.php

include_once 'include/functions.php';


The Fix


include_once 'functions.php';

OR

include_once __DIR__ . 'functions.php'; //PHP 5.3 or higher

OR

include_once dirname(__FILE__) . 'functions.php'; //PHP 5.2 or lower


The Reason


head.php and connect.php are located in the same folder as functions.php

As suggested by @Schleis, using __DIR__ (PHP 5.3+) or dirname(__FILE__); (PHP 5.2-) will allow for relative file includes.

Use the constant __DIR__ in your include statements and then move relative to that. So in sub/index.php you would do include_once __DIR__ . '../include/connect.php'

The __DIR__ is a constant that is the directory of the file that you are in.

http://php.net/manual/en/language.constants.predefined.php

If you are using php < v5.3, you can use dirname(__FILE__) to get the same thing.

I would suggest to set your web project root directory in every file using chdir() function, so you don't need to think about it where are you currently located and how many back-dirs ../ you need.

Use example:

chdir($_SERVER['DOCUMENT_ROOT']);

You could define constant for include path in root file and then use that constant in all other files:

define( "INCLUDE_PATH",  dirname(__FILE__) . '/include/' );

// some other file
include_once INCLUDE_PATH . 'functions.php';

It is good practice to have one file like config.php in the root folder where are defined global settings like include paths etc. That way you do not have to care about relative paths anymore, and if in the future you decide to change the folder structure, instead of changing the paths in all files just change the include constant.