Reputation: 83
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.
Upvotes: 2
Views: 14724
Reputation: 1
include "include/header.php";
include "include/head.php";
if you are select file from an other folder then coding will be like this
include "foldername/filename.php";
Upvotes: 0
Reputation: 664
I do this by creating a variable on the beginning of every page. The variable is simply the path to the top level directory.
example...
instead of
include 'includes/head.php';
use:
$pathToRoot = '../';
include $pathToRoot.'includes/head.php';
but you will have to create this variable on the top of every page and change all include and require statements.
Upvotes: 1
Reputation: 18933
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
$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');
Upvotes: 7
Reputation: 96
You can check this part of the PHP documentation : http://www.php.net/manual/en/function.include.php
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.
I suggest you either :
php.ini
) so you won't have any problems!Also, when you say :
for example i have this include in my postpage.php which is located at example.com/c/postpage.php:
Be sure to understand fully the fact that the "path" URL (example.com/foo) and the path file on the disk can be totally different, and totally unlinked.
So, in your case, as you seems to have one directory for layout stuff (header/footer/...) and maybe one other for templates, the easiest thing is probably to add these 2 paths in your php.ini.
Then just call : include('head.php')
and you're done.
You can also just add in your include_path the base directory of your project, and then call include('includes/overall/head.php')
Upvotes: 1