获取父目录的相对路径 [英] Get relative path to a parent directory
问题描述
我有一个场景,我想获取返回特定父目录的路径.这是一个示例文件夹结构([something]
是一个文件夹)
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');
?>
这适用于 index.php
但不适用于 somePage.php
和 someSubPage.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 ../../
.
我想过使用 __FILE__
然后只计算给定 $rootDirName 和字符串结尾之间的 /
字符.但是,我想问一下这是否是一种可靠的方法以及它在 PHP 中的外观.(我对 PHP 的工作并不多......)
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...)
推荐答案
可以使用..
进入上级目录:
You can use ..
to get into the parent directory:
<?php
// somePage.php
include('../components/header.php');
?>
这篇关于获取父目录的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!