user2360599 user2360599 - 1 year ago 85
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

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 Source

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.


File structure:

serverRoot (/)

let's say that:

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


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


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


global $basedir;
include($basedir . '/includes/overall/c.php');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download