【问题标题】:PHP include files from different foldersPHP包含来自不同文件夹的文件
【发布时间】:2018-07-18 13:48:27
【问题描述】:

我有 2 个文件 index.php 和 header.php,它们都在不同的文件夹中。

root/en/index.php

root/includes/header.php

我尝试使用 config.php 文件(放置在根目录中)设置根文件夹:

DEFINE("ROOT_PATH", dirname( __FILE__ ) ."/" );

在 index.php 中,如果我尝试包含任何页面(header.php 或 confing.php),路径仍然从 index.php 子文件夹 (en) 开始,而不是从根目录开始。在 index.php 我使用:

include( ROOT_PATH . "/config.php");

include( ROOT_PATH . "/includes/header.php");

结果是:

警告:使用未定义的常量 ROOT_PATH - 假定为“ROOT_PATH”

警告:include(ROOT_PATH/config.php):打开流失败:root/eng/index.php 中没有这样的文件或目录。


所以我尝试不使用 confing.php(因为我虽然将文件包含在子文件夹中会更改根文件夹)但它仍然不起作用..

我在本地主机上,使用 XAMP。

【问题讨论】:

  • 你必须阅读你的错误
  • 你的文件是 root/en/index.php 吗?我认为应该是 root/eng/index.php
  • @executable 就在那里。错误消息中有很多信息表明您的常量定义不正确,因此路径构建不正确。另一种解决方案是使用上升的相对路径,例如include '../includes/header.php'; 应该允许您从 index.php 中包含该文件。但是,如果您在尝试时收到新的错误消息,您应该再次阅读并解释它们。
  • index.php 放在 root/en 文件夹中。对不起,“eng”我修改了路径,在这里看起来很简单,并且不小心输入了 eng 而不是 en。问题是我无法从 root/en/ 转到 root
  • 我猜你们俩都在引用未正确定义的 ROOT 常量。我已经在论坛和教程上了解了它是如何工作的,看起来很好,我不明白为什么它不起作用......

标签: php include directory root


【解决方案1】:

你知道吗,你可以像这样使用包含:

include '../../config.php'; 

【讨论】:

  • 由于某种原因它不起作用并返回相同的错误:警告:包含(../../includes/header.php):打开流失败:没有这样的文件或目录在 C:\xampp\htdocs\root\en\index.php 第 20 行
  • config.php文件位置在哪里,你调用config.php目录在哪里?
  • root/confing.php 我在 root/en/index.php 中调用它 - 所以我必须更上一层楼,我尝试了 ../confing.php、./config.php 和你的答案路径,它不起作用..
  • 你能把 index.php 文件贴在这里吗?
  • 所以.. 它从 /root/en/index.php 使用 include '../config.php;我不知道,因为我只测试了 include '../includes/header.php';并且由于某种原因,XAMP 没有在文件夹中显示此文件,因此 PHP 代码无论如何都找不到它......问题是我不能对整个站点使用“../path”,因为它不是使用静态路径非常安全。我不知道如何发布索引文件抱歉
【解决方案2】:
/** This must be done in the same file. 
  *  (Or in a file whose import does not depend on the 'ROOT_PATH' constant.)
  **/
define('ROOT_PATH', dirname( __FILE__ ) ."/" );

include( ROOT_PATH . "/config.php");

include( ROOT_PATH . "/includes/header.php");

【讨论】:

    【解决方案3】:

    你有 config.php

    DEFINE("ROOT_PATH", dirname( __FILE__ ) ."/" );
    

    它本身有 ROOT_PATH 的定义。所以当你需要 ROOT_PATH 时,你需要先包含 config.php。

    如果 config.php 文件位于 root/config.php 中,并且您需要从 root/en/index.php 调用该文件,那么您需要拥有,

    include(dirname(__DIR__).'/config.php');
    include( ROOT_PATH . "/includes/header.php");
    

    那么代码就可以工作了。

    编辑:

    echo dirname(__DIR__).'/config.php'
    exit;
    

    在您正在调用的文件上运行此代码。您知道要包含的文件是什么,并检查您在代码中获得相同目录信息的目录结构

    【讨论】:

    • 我试过了,还是不行。据我了解,当 config.php 包含在 index.php 中时,代码将运行并且根目录将是 index.php 所在的位置(所以 root/en/..)
    • 我假设您将 root/ 定义为您的 ROOT_PATH 并且配置文件位于 root/config.php 中,并且您正在从 root/en/index.php 调用该文件。如果不是让我知道 config.php 文件的位置
    • 你是对的。配置文件位于根文件夹中。
    • 我认为您可能有两个版本的 xampp 并安装在两个不同的驱动器/目录中,并在运行另一个版本的 xampp / apache 的情况下运行代码。
    猜你喜欢
    • 2016-05-23
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    相关资源
    最近更新 更多