【问题标题】:Using $_SERVER['DOCUMENT_ROOT'] means I can't access variables in an included file使用 $_SERVER['DOCUMENT_ROOT'] 意味着我无法访问包含文件中的变量
【发布时间】:2017-12-29 00:44:08
【问题描述】:

我在 header.php 文件中调用了一个数据库配置文件 (db_config.php)。我在我的模板(location.php)中调用 header.php 我需要访问 db 配置文件中的变量,因为我正在运行返回结果的查询,然后我在模板中调用它。

所以在我的 db_config.php 文件中,我有以下内容:

$area_query = "SELECT * FROM `locations` where `type` = 'area'";

mysqli_query($db, $area_query) or die('Error querying database.');

$area_result = mysqli_query($db, $area_query);

if (!$area_result) {
  printf("Error: %s\n", mysqli_error($con));
  exit();
}

然后在一个名为 locations.php 的文件中,我正在循环遍历结果 以上使用:

            while ($row = mysqli_fetch_array($area_result))
        {
            echo "<li class='location-list-item'><a href='location/$row[name]'><span class='initial-letter'>".mb_substr($row['name'],0,1)."</span>".$row['name']." <i class=\"fa fa-chevron-circle-right\" aria-hidden=\"true\"></i></a></li>";
        }

如果我使用以下方法在 header.php 中包含 db_config.php,这将正常工作:

include("config/db_config.php");

但是,如果我使用:

include($_SERVER['DOCUMENT_ROOT']."/config/db_config.php");

它按预期找到了 db_config.php(访问locations.php 文件时在db_config.php 输出中回显某些内容),但我无法访问$area_result。我收到以下错误:

Notice
: Undefined variable: area_result
on line
28


Warning
: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null 
given in
locations.php
on line
28

我很困惑为什么使用 $_SERVER['DOCUMENT_ROOT'] 会阻止我访问变量?出于文件路径的原因,我需要使用 $_SERVER['DOCUMENT_ROOT']。

为了澄清,我在locations.php 中包含了header.php,而header.php 又包含了db_config.php。我可以在 db_config 中回显访问locations.php 时输出的内容,但我无法访问变量。

谢谢。

【问题讨论】:

标签: php variables document-root server-side-includes


【解决方案1】:

我首先建议您回显 $_SERVER['DOCUMENT_ROOT'] 的返回值,以确保它显示您期望的路径。当然,在本地环境中执行此操作。

<?php echo $_SERVER['DOCUMENT_ROOT']; ?>

您的配置目录(用于 include() 的部分路径)需要直接位于您的文档根目录中,该路径才能正常工作,这就是为什么检查首先返回的路径将有助于您解决此问题的原因。

您可能需要调整路径以更准确地匹配您要包含的文件所在的位置。

<?php include($_SERVER['DOCUMENT_ROOT'] . "/SOME_DIR/config/db_config.php"); ?>

您的另一个选择是,如果您想将该文件包含在多深度目录中的多个文件中,那么您也可以像这样使用双点形成相对路径...

<?php include('../config/db_config.php'); ?>

以上将允许您访问位于当前目录上方的 config/db_config.php 文件,以下将允许您访问当前文件所在当前目录上方两个目录的文件。

<?php include('../../config/db_config.php'); ?>

附带说明一下,最好使用 include_once 来避免多次包含文件,或者甚至更好的是 require_once,它可以让您使用文件中的内容而无需将其实际编译为该文件的一部分。

您可以尝试的最后一件事,虽然我不确定这是否仅适用于面向对象编程 (OOP),但您可以尝试在使用之前将变量标记为全局变量。

<?php

global $area_result;

while ($row = mysqli_fetch_array($area_result)) {
    echo "<li class='location-list-item'><a href='location/$row[name]'><span class='initial-letter'>".mb_substr($row['name'],0,1)."</span>".$row['name']." <i class=\"fa fa-chevron-circle-right\" aria-hidden=\"true\"></i></a></li>";
}

?>

希望我能帮助您并解决您的问题。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多