【问题标题】:PHP Dynamic include based on current file path基于当前文件路径的 PHP 动态包含
【发布时间】:2010-04-11 17:23:44
【问题描述】:

我想根据当前文件路径找到一种方法来包含一些文件..例如:

我有“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-once]: http:// wrapper is disabled in server configuration by allow_url_include=0”之类的错误..因为被禁用且不安全..

有没有办法做到这一点? 谢谢!

【问题讨论】:

    标签: php dynamic include filenames


    【解决方案1】:

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

    【讨论】:

      【解决方案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" />
      

      【讨论】:

      • 通常,仅代码的答案被认为质量差。也许你可以提供一个关于这里发生了什么的解释?
      【解决方案3】:

      我会做一些简单的事情:

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

      您的 HTTP 包装问题似乎与此无关。你说的超越是什么意思?您通常永远不想进行远程包含。

      【讨论】:

        【解决方案4】:

        为什么不以简单的方式来做呢:

        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;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-24
          • 2015-11-01
          • 1970-01-01
          相关资源
          最近更新 更多