I have a scenario where I want to get a path back to a specific parent directory. Here is an example folder strcuture ([something]
is a folder)
index.php
[components]
header.php
footer.php
[pages]
somePage.php
[somePageSubPages]
someSubPage.php
So my content pages look something like this:
<?php
include('components/header.php');
?>
<!-- CONTENT STUFF -->
<?php
include('components/footer.php');
?>
This works for the index.php
but not for somePage.php
and someSubPage.php
. What I want to do is create a function that returns the path back to the main directory so I can then add this to the includes and other stuff:
$relPath = getPathToRoot($rootDirName);
include($relPath . 'components/header.php');
And the function only would return an empty string or ../../
.
I thought about using __FILE__
and then just count the /
-characters between the given $rootDirName and the the string end. However, I would like to ask if this is a reliable way and how this would look in PHP. (I don't realy work that much with PHP...)
I would make sure that you always know the root of your site so that you can take it from there.
To do that, you could go at least two ways:
include MY_SITE_ROOT . '/path/to/file.php';
include $_SERVER['DOCUMENT_ROOT'] . '/path/to/file.php';
You can use
..
to get into the parent directory: