Get relative path to a parent directory

2020-04-19 03:12发布

问题:

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...)

回答1:

You can use .. to get into the parent directory:

<?php
    // somePage.php
    include('../components/header.php');
?>


回答2:

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 a config file that defines your site-root and prepend that root to every include like (in case of a constant):
    include MY_SITE_ROOT . '/path/to/file.php';
  • Use a server variable to achieve the same like:
    include $_SERVER['DOCUMENT_ROOT'] . '/path/to/file.php';