包含父目录或其他目录中的文件

Dar*_*ren 39 php

我需要将父目录和其他子目录中的文件包含到子目录中.我以前只使用include('/ rootdirectory/file.php')就完成了; 但现在它似乎不起作用.

只是想知道我怎么能这样做,谢谢.

这是我的确切行:

include('/forums/groups.php');
Run Code Online (Sandbox Code Playgroud)

它给了我这个错误(页面仍然运行):

警告: include(/forums/groups.php)[function.include]:无法打开流:C:\ xampp\htdocs\forums\blog\posts.php中没有这样的文件或目录

警告: include()[function.include]:在C:\ xampp\htdocs\forums\blog中打开'/forums/groups.php'以包含(include_path ='.; C:\ xampp\php\PEAR')失败\ posts.php在第3行

Mic*_*ski 77

include()它的亲属采用文件系统路径,而不是相对于文档根目录的Web路径.要获取父目录,请使用../

include('../somefilein_parent.php');
include('../../somefile_2levels_up.php');
Run Code Online (Sandbox Code Playgroud)

如果以a开头,/将使用绝对系统文件路径:

// Full absolute path...
include('/home/username/sites/project/include/config.php');
Run Code Online (Sandbox Code Playgroud)

  • @thanassis我不知道你为什么在不知道文件系统布局的情况下失败了.具体来说,在主文件所在的目录中以及所包含文件所在的目录中.当您的应用程序更改工作目录(Drupal执行此操作)时,它也可能是一个问题,然后您需要通过`dirname(__ FILE__)的绝对路径.'/ path/to/file.php'`在另一个解决方案中. (4认同)
  • 尝试这样做,它与问题无关,因为我有同样的问题. (3认同)

Ste*_*gin 9

如果您的服务器没有解析父目录使用的文件

include '../somefilein_parent.php'

试试这个:

include __DIR__ . "/../somefilein_parent.php";


Fra*_*ank 6

这是我写的那个问题:

<?
function absolute_include($file)
         {
         /*
         $file is the file url relative to the root of your site.
         Yourdomain.com/folder/file.inc would be passed as
         "folder/file.inc"
         */

         $folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");

         if($folder_depth == false)
            $folder_depth = 1;

         include(str_repeat("../", $folder_depth - 1) . $file);
         }
?>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


Chr*_*ker 5

取决于您尝试包含的文件所在的位置。

例子:

/rootdir/pages/file.php

/someotherDir/index.php

如果你在 index.php: 中写了以下内容: include('/rootdir/pages/file.php');它会出错,因为它会尝试获取:

/someotherDir/rootdir/pages/file.php 哪个当然不存在...

所以你必须使用 include('../rootdir/pages/file.php');