Get relative path to a parent directory

只愿长相守 提交于 2019-12-02 07:13:36

问题


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';


来源:https://stackoverflow.com/questions/25413877/get-relative-path-to-a-parent-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!