基于当前文件路径的PHP动态包含

14
我想找到一种方法,根据当前文件路径来包含一些文件。例如:
我有一个"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"。
此外,我希望解决“Warning: include_once() [function.include-once]: http:// wrapper is disabled in the server configuration by allow_url_include=0”这种错误,因为它被禁用并且不安全。
有没有办法实现这一点?谢谢!
4个回答

35

我认为你需要使用 __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 目录分隔符是不同的,你的解释器会在不同的平台上使用适当的值。


3
您可以将所需的内容放置在条件逻辑内部。
<?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" />

2
通常,仅包含代码的答案被认为是质量较差的。也许您可以提供一小段解释,说明这里发生了什么? - corsiKa

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接