2010-04-11 70 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