doublestar2014
2014-03-17 11:06
浏览 176
已采纳

PHP:使用绝对路径在include / require文件中定义的变量不可访问

I am finding difficulty in accessing a variable defined in the include file.

My include file is present in the root and it has a variable $x:

localhost/dir_name/include.php

I am including the include.php file in file.php present in the sub directory :

localhost/dir_name/sub_directory/file.php

But every time, the file.php gives the error of undefined variable $x

The weird thing is that when I use a relative path to include the include.php, it works perfectly. Like this:

include '../include.php';

ALSO, it works when using realpath($_SERVER['DOCUMENT_ROOT']). Like this:

include $_SERVER['DOCUMENT_ROOT'].'\dir_name\include.php'

But it never works for the absolute path. I also tried making the variable global but didn't helped me and the include.php file is also included correctly. It is not giving me any other error except this undefined variable.

Before asking, I tried finding this on SO, but couldn't find the answer to this error.

I am currently using the realpath($_SERVER["DOCUMENT_ROOT"]) as an alternative.

图片转代码服务由CSDN问答提供 功能建议

我发现难以访问包含文件中定义的变量。

我的包含文件存在于根目录中,它有一个变量 $ x

localhost / dir_name / include.php < / p>

我在子目录中的 file.php 中包含 include.php 文件:

localhost / dir_name / sub_directory / file.php

但每次,file.php都会出现 undefined variable $ x <的错误 / code>

奇怪的是,当我使用相对路径来包含 include.php 时,它可以很好地工作。 像这样:

include'../include.php';

nn

ALSO,它在使用<代码时有效 >真实路径($ _ SERVER [ 'DOCUMENT_ROOT'])。 像这样:

包括$ _SERVER ['DOCUMENT_ROOT']。'\ dir_name \ include.php'

但是 它永远不会适用于绝对路径。 我也尝试使变量全局但没有帮助我, include.php 文件也正确包含在内。 除了这个未定义的变量之外,它没有给我任何其他错误。

在询问之前,我尝试在SO上找到它,但找不到这个错误的答案。

我目前正在使用 realpath($ _ SERVER [“DOCUMENT_ROOT”])作为替代方案。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanliusong6395 2014-03-17 11:09
    已采纳

    localhost is not an absolute path. PHP reads the actual directories on your computer, not the ones from the URL.

    Try echo realpath($_SERVER["DOCUMENT_ROOT"]) and you'll see what I mean.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题