Php 冲突,包括具有相对路径的文件

Php 冲突,包括具有相对路径的文件,php,include,relative-path,Php,Include,Relative Path,我正在尝试在我的php脚本中动态创建包含。这是我的目录树: -index.php -sources/ --hello.php --bye.php 在我的index.php中,我包含了hello.php: include("sources/hello.php"); 在我的hello.php中,我还包括: include("bye.php"); 当我访问index.php时,它抛出一个错误,说: 信息: 需要一次(bye.php) [function.require once]:无法打开流:没

我正在尝试在我的php脚本中动态创建包含。这是我的目录树:

-index.php
-sources/
--hello.php
--bye.php
在我的
index.php
中,我包含了hello.php:

include("sources/hello.php");
在我的
hello.php
中,我还包括:

include("bye.php");
当我访问
index.php
时,它抛出一个错误,说:

信息: 需要一次(bye.php) [function.require once]:无法打开流:没有此类文件或 目录

有没有办法让它工作但没有绝对的路径?因为路径可以从一个目录更改到另一个目录,但保持结构不变:

-index.php
-sources/
--hello.php
--bye.php
为什么不使用

index.php的内容

include(getcwd() . "/sources/hello.php");
include(getcwd() . "/sources/bye.php");
hello.php的内容

include(getcwd() . "/sources/hello.php");
include(getcwd() . "/sources/bye.php");
使用

像这样

include(dirname(__FILE__)."/bye.php");
由于“hello.php”被包含在“index.php”中,“bye.php”需要被包含在“hello.php”中,就像它被包含在“index.php”中一样。 像这样:

include("sources/hello.php");
$webroot = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
include($webroot."sources/bye.php");

OUTPUT -->http://website.com/sources/bye.php
但是,如果您想将“hello.php”包含在所有地方,而不仅仅是“index.php”目录中,那么可以在“hello.php”中设置一个变量,每次都为您提供正确的路径。 像这样:

include("sources/hello.php");
$webroot = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
include($webroot."sources/bye.php");

OUTPUT -->http://website.com/sources/bye.php

查看此内容了解为什么dirname+\uuuuu文件比getcwd更好