2010-04-11 68 views
11

上,我想找到一種方法,包括基於當前的文件路徑上的一些文件。例如:PHP動態包括基於當前的文件路徑

我有「website.com/templates/name1/index.php 「,這個」index.php應該是一個獨特的文件,我將在不同深度的許多不同目錄中使用,所以我想使代碼具有通用性,因此我不需要在該文件內部更改任何內容。「

所以如果這個「index.php」位於

」website.com /templates/name1/index.php「

比它應該包括位於這裏的文件:

website.com/content /templates/name1/content.php」

另一個例子:

website.com /templates/name2/index.php」

比它應該包括文件位置爲:

website.com/content /templates/name2/content.php」

此外想超限「警告:include_once()的[一次function.include]:HTTP://封裝被禁用在服務器配置中通過allow_url_include = 0「類型的錯誤..因爲被禁用和不安全..

有沒有辦法實現這個? 謝謝!

回答

31

我認爲你需要使用__FILE__(它在一開始,並在名稱末尾兩個下劃線)和DIRECTORY_SEPARATOR常數基於當前的文件路徑上的文件工作。

例如:

<?php 
    // in this var you will get the absolute file path of the current file 
    $current_file_path = dirname(__FILE__); 
    // with the next line we will include the 'somefile.php' 
    // which based in the upper directory to the current path 
    include(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'somefile.php'); 

使用DIRECTORY_SEPARATOR常數比使用更安全 「/」(或「\」)符號,因爲Windows和* nix目錄分隔符是不同的,你的解釋器將在不同的平臺上使用適當的值。

0

我只是做一樣簡單的東西:

$dir = str_replace('website.com/','website.com/content/',__DIR__); 
include "$dir/content.php"; 

而且你的HTTP包裝的問題似乎並沒有有什麼與此有關。超越它意味着什麼?你通常不想做一個遠程包含。

-1

爲什麼不這樣做的簡單的方法:

dirname(__FILE__); //Current working directory 
dirname(dirname(__FILE__)); //Get path to current working directory 

然後終於

$include_path = $dir_path . 'file_to_include.php'; 
include $include_path; 
2
<?php 
if (isset($_GET['service'])) { 
    include('subContent/serviceMenu.html'); 
} else if (isset($_GET['business'])) { 
    include('subContent/business_menu.html'); 
} else if (isset($_GET['info'])) { 
    include('subContent/info_menu.html'); 
} 
else { 
    include('subContent/banner.html'); 
} 
?> 
<a href="http://localhost/yourpage.php?service" /> 
+1

一般來說,代碼只-答案被認爲是質量差。也許你可以提供一個解釋這裏發生了什麼的片段? – corsiKa 2012-11-13 19:02:32