2012-10-17 74 views
3

我试图使我的PHP脚本动态地包括。这是我的目录树:冲突包括具有相对路径的文件

-index.php 
-sources/ 
--hello.php 
--bye.php 

在我index.php我做一个包括hello.php的:

include("sources/hello.php"); 

在我hello.php我还有另外包括:

include("bye.php"); 

当我访问index.php它会抛出一个错误说:

消息: require_once(bye.php)一次function.require] :未能打开流:没有这样的文件或目录

有没有办法得到它的工作原理,但没有绝对的路径?由于路径可以是可变的从一个目录到另一个但保持结构:

-index.php 
-sources/ 
--hello.php 
--bye.php 

回答

3

使用

dirname(__FILE__); 

这样

include(dirname(__FILE__)."/bye.php"); 
+0

那是我一直在寻找的!非常感谢 :) – manix

1

为什么不使用getcwd()

index.php内容:的hello.php

include(getcwd() . "/sources/hello.php"); 

内容:

include(getcwd() . "/sources/bye.php"); 
+1

工作呢!谢谢:) – manix

+2

看到这个知道为什么dirname + __ FILE__比getcwd更好http://stackoverflow.com/questions/2184810/difference-between-getcwd-and-dirname-file-which-should-i-use – mbouzahir

0

由于“index.php”中包含“hello.php”,所以“bye.php”需要包含在“hello.php”中,就好像它包含在“index.php”中一样。 像这样:

include("sources/hello.php"); 

但是,如果你想包括“hello.php”扩展所有的地方,而不是仅在“的index.php”目录中,您可以设置在“hello.php”扩展变量每次给你正确的路径。 想要这样:

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

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