将文件从一个目录包含到同一级别的另一个目录不起作用

Include a file from one directory to another in the same level not working

好的,所以我想在我的 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

使用 .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 可能与您已经遇到的路径问题相同。最好的解决方案是使用单个文件来加载所有页面,但该讨论超出了您的问题范围。

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

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

有关参考,请参阅