user2360599 user2360599 - 3 days ago 5
PHP Question

PHP include files from another directory that also include files

I have includes in multiple files, i recently started a new directory and am unable to get some of my includes to work.

for example i have this include in my postpage.php which is located at example.com/c/postpage.php:

include '../includes/overall/header.php';


which works as it goes to the root directory and includes header.php
but my problem is that header.php also includes files which are not being included.

the code in header.php is:

include 'includes/head.php';


which is not working

if i change header.php to:

include '../includes/head.php';


then it breaks the rest of my site, while working only for postpage.php

any advice is welcome.

Answer

The best way, to prevent changes in CWD that might break relative paths is to include files using absolute paths.

An easy way to accomplish this is by using the __DIR__ constant.

Example:

File structure:

serverRoot (/)
    |-usr
        |-local
            |-www
                |-index.php
                |-bootstrap.php
                |-includes
                    |-a.php
                    |-overall
                        |-b.php
                        |-c.php

let's say that:

  • index.php includes bootstrap.php and a.php
  • a.php includes b.php
  • bootstrap.php includes c.php

index.php

$basedir = realpath(__DIR__);
include($basedir . '/bootstrap.php');
include($basedir . '/includes/a.php');

a.php

global $basedir;
include($basedir . '/includes/overall/b.php');

bootstrap.php

global $basedir;
include($basedir . '/includes/overall/c.php');
Comments