Php 包括来自其他目录的文件

Php 包括来自其他目录的文件,php,file,include,Php,File,Include,目前,我正在尝试从另一个目录中包含一个PHP文件 public_html/a/class/test.php <-- from this file i would to include a file from public_html/b/common.php <-- wanted to include this file 这会继续为我返回public\u html/a/ 我试过这样的东西 dirname(__FILE__).'/../b/common.php' 但这对我获取文件没

目前,我正在尝试从另一个目录中包含一个PHP文件

public_html/a/class/test.php <-- from this file i would to include a file from
public_html/b/common.php <-- wanted to include this file
这会继续为我返回
public\u html/a/

我试过这样的东西

 dirname(__FILE__).'/../b/common.php'
但这对我获取文件没有帮助

include('../../b/common.php');

要为您包含文件,请确保两个目录都具有与用户相同的用户组。

您只需继续向上移动目录树,直到拥有共同的祖先:

require dirname(dirname(__DIR__)) . '/b/common.php';
魔法常数
\uuuu DIR\uuuu
等于
dirname(\uuuu FILE\uuuu)
,并在5.3中引入。每次使用
dirname()
都会返回一个目录,即:

dirname('public_html/a/class'); // public_html/a
dirname('public_html/a'); // public_html

顺便说一句,PhpStorm等编辑器也理解相对路径的这种用法。

首先,我建议您为basepath定义一个变量,并将定义的变量包含在相对文件中

// This should be on any root directory file
define("PR_BASEPATH", dirname(__FILE__));
根据你的实现,假设你在

public_html/a/class/test.php
dirname(\uuuu FILE\uuuuu)
返回当前文件的目录名,该文件根据
test.php
文件始终返回目录
class

您希望包含另一个目录
/b
中的
public\u html/b/common.php
。因此,您必须首先获取文档根目录

include $_SERVER['DOCUMENT_ROOT'] . "/b/common.php";

看看

dirname(\uuuuu文件)
应该是
public\uhtml/a/class
,如果是,你需要
dirname(\uu文件)'//b/common.php“
似乎在工作..但是想知道/./做什么呢?仅供参考
\uuuuu DIR\uuuuu==dirname(\uuu FILE\uuuu)
每个
。/
上升一级。因此,如果你从
public\u html/a/class
开始,你需要上两层回到
public\u html
才能到达
/b
如果
public\u html
是你的
文档根目录
,你也可以做
$\u服务器['DOCUMENT\u ROOT']/b/common.php'
我建议不要依赖
文档根目录
。首先,它不是在非web上下文(CLI、cron作业等)中设置的。其次,如果将应用程序移动到子目录,则所有路径都将不正确。使用来自
\uuuu DIR\uuuu
的相对路径是best@Phil很公平,删除:)
include $_SERVER['DOCUMENT_ROOT'] . "/b/common.php";