PHP - 带有相对路径的include()或require()在Windows上不起作用,即使在追加__DIR__时也是如此

mic*_*ael 3 php relative-path require include

我在这里阅读有关PHP的问题,当使用带有相对路径的include()或required()时,我看到的所有解决方案都是附加DIR

我目前正在使用Windows,即使错误消息显示DIR的当前值,然后相对路径似乎被添加为字符串,而不是向上升级,例如:

include(__DIR__ . "..\\another_folder\\file_2.php");
Run Code Online (Sandbox Code Playgroud)

产生以下错误:警告:include(C:\ xampp\htdocs\main_folder ..\another_folder\file_2.php)[function.include]:无法打开流:没有这样的文件或目录

知道发生了什么事吗?

rid*_*rid 21

您需要\在目录名称后添加:

include(__DIR__ . "\\..\\another_folder\\file_2.php");
Run Code Online (Sandbox Code Playgroud)

这将使路径成为

C:\ XAMPP\htdocs中\ main_folder\..\another_folder\file_2.php

代替

C:\ XAMPP\htdocs中\ main_folder ..\another_folder\file_2.php

此外,为了便于携带,建议使用/而不是\,它适用于所有平台,包括Windows:

include(__DIR__ . "/../another_folder/file_2.php");
Run Code Online (Sandbox Code Playgroud)