My PHP files in my root directory INCLUDE header.php. Header.php INCLUDEs functions.php. I\'m adding new pages in a subdirectory, so I added leading slashes to all my links
Standard Paths 101:
/path/somefile
- the leading /
anchors this path structure at the ROOT of the file system, e.g. it's the equivalent of C:\path\somefile
.
path/somefile
- no leading /
. The OS will use the programs "current working" directory as the basis of the path, so if you're in a shell that's in /home/foo
, then somefile
will be search for in /home/foo/path/somefile
.
../somefile
. the ..
refers to the PARENT directory of the current working directory, so if you're in /home/foo
, then ../somefile
will be searched for as /home/somefile
.
Note that you can have non-sensical paths like
/../../../../somefile
. This will be acceptable, but is pointless, as you're both anchoring the path at the root of the file system, then trying to go ABOVE the root, which is not possible. This path is the operational equivalent of /somefile
.
Just so you're aware, if you're going to have the php pages you're requesting also request other pages themselves, it may be beneficial to use require_once
instead of include
. That will make it so none of the pages that are included repeat themselves and you don't have to worry about accidentally including something more than once.
That being said... when you request a page in the root directory, it will request header.php in the root directory which will in turn request functions.php in the root directory. However, if you request from the subdirectory, ../header.php
will reference header.php in the root directory, but that whole file will get included, and then its the php page in the subdirectory that ends up trying to include /functions.php
. It would need to request ../functions.php
, but that would cause everything in the root directory to stop working.
I'd suggest setting a variable in header.php along the lines of $root = $_SERVER['DOCUMENT_ROOT'];
Then, all includes in header.php should be like include($root."/functions.php");
$_SERVER['DOCUMENT_ROOT']
will get you objective url to the root, which will enable you to make sure you're referencing the correct place no matter where you're requesting header.php from.
Include
and Require
literally pull the code into the executing file, so one thing to watch out for is that the files in a subdirectory are running from the working directory.
Example:
|-templates-|-header.php
Docroot--|
|-inc-|-functions.php
|
|-index.php
Index.php
<?php
include 'template/header.php';
...
?>
template/header.php
<?php
include 'inc/functions.php';
...
?>
because the header.php code is being executed from the docroot due to the include.