将一个目录中的文件包含在同一级别的另一个目录中

时间:2016-01-01 23:52:28

标签: php include

好的,所以我想在我的WEBROOT/common/header.php

中添加一个header.php

但如果我尝试将其包含在WEBROOT/legal/legal.php中的文件中,则无效。

我试过以下

include 'common/header.php';
include '/common/header.php';
include './common/header.php';
include '../common/header.php';
include __DIR__ . 'common/header.php';
include 'http://siteurl.com/common/header.php';

文件结构似乎足够基本

index.php
-/common/header.php
-/legal/legal.php

2 个答案:

答案 0 :(得分:0)

使用.php.ini创建可存储DocumentRoot的配置文件。

.php方法:

if (!defined('_BASE_DIR_')) {
    define('_BASE_DIR_', '/var/www/html/site');
}

然后在代码中使用此常量,如下所示:

require_once 'constants.php';
require_once _BASE_DIR_.'/legal/legal.php';

.ini方法:

[common]
base_dir=/var/www/html/site

阅读 .ini 文件,如下所示:

$ini = parse_ini_file('config.ini', true);

然后包括如下文件:

require_once $ini['common']['base_dir'].'/legal/legal.php';

请注意,读取常量的require或parse_ini_file可能与您遇到的路径问题相同。最好的解决方案是使用单个文件加载所有页面,但该讨论不在您的问题范围内。

答案 1 :(得分:0)

最好的解决方案是将__DIR__常量与require结合使用,如前所述。请注意,在您的示例中,您仍然缺少目录分隔符:

require __DIR__ . '/../common/header.php';

供参考,见

相关问题