2012-10-17 70 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