【问题标题】:Included file from a parent folder that includes a file from another folder父文件夹中包含的文件,其中包含另一个文件夹中的文件
【发布时间】:2012-06-13 18:01:15
【问题描述】:

标题很难理解,但我的问题很简单:

我有:

config.php

include('config_mysql.php');
include('language/english.php');

然后我有:index.php

include('config.php');

然后:/ajax/ajax_vote.php

include('../config.php');

为什么index.php 包含config_mysql.phplanguage/english.phpajax/ajax_vote.php 只包含config_mysql.php

【问题讨论】:

    标签: php include directory


    【解决方案1】:

    include() 的基本文件夹始终是原始脚本的基本文件夹,因此 include()s 内的 include()d 脚本将不直观:

    ajax/ajax_vote.php 将(尝试)包括

    ajax/../config.php
      -> ajax/sonfig_mysql.php
         ajax/language/english.php
    

    你可能想看看

    $BASEDIR=dirname(__FILE__);
    include("$BASEDIR/config_mysql.php");
    include("$BASEDIR/language/english.php");
    

    和朋友。

    【讨论】:

    • 不,在我的情况下,它实际上包含基本文件夹中的 config_mysql.php(我保证!),唯一的问题是语言文件夹中的 english.php 文件
    【解决方案2】:

    原因是language/english.phpconfig.php 不在同一目录中。此外,/ajax/ajax_vote.php 位于根文件夹之外。

    但是,PHP 仍然能够正确地包含文件。我不明白为什么/ajax/ajax_vote.php 不包括文件language/english.php。如果我误解了这个问题,请纠正我。

    【讨论】:

    • 完全正确,就是这样。 ajax_vote.php 不包括文件 language/english.php 但确实包括 config_mysql.php strage...还有其他人吗?
    【解决方案3】:

    Eugen 说的是真的,这是因为基本路径与您包含的脚本不同。

    从我的测试看来(因为我遇到了类似的问题)php include() 在包含文件时会存储另一个临时的 include_path,这就是为什么 ajax_vote.php 可以包含 config_mysql.php。为了说服自己,请尝试将 config_mysql.php 移动到您的 ajax 文件夹:它的工作方式相同,并且 config.php 将能够包含它(但仅在执行 ajax_vote.php 时,而不是 index.php!)。在这种情况下,您有两个包含路径:'/ajax/' 和 '/'。

    但是,当您使用路径(不仅仅是要包含的文件名,还要在字符串中指定文件夹)时,包含路径仅基于执行脚本(例如:仅 '/ajax/')。

    您可以通过以下方式解决此问题:

    include(dirname(__FILE__).'/language/english.php'); // don't forget the prepended '/'
    

    或者只是:

    include('/language/english.php'); // here again the prepended '/'
    

    但是我警告你,我还不完全理解为什么第二种方法有效,你可以通过使用第一种方法和 dirname() 更安全。

    /EDIT:我刚刚发现 include('/path/to/file') 可能是 Windows 操作系统上的一个错误:在 Windows 上它等于 dirname(__ FILE__ ),但在 UNIX 上它等于根路径。所以 dirname(__ FILE__ ) 肯定更可靠。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2014-09-18
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2012-06-03
      相关资源
      最近更新 更多