PHP - 带有相对路径的 include() 或 require() 在 Windows 上不起作用,即使附加 __DIR__

发布于 2025-01-05 12:34:38 字数 411 浏览 4 评论 0原文

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

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

include(__DIR__ . "..\\another_folder\\file_2.php");

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

知道发生了什么吗?

I was reading here about problems in PHP when using include() or required() with relative paths and all the solutions I saw was to append DIR

I'm currently working on Windows, and even though the error message displays the current value of DIR, then the relative path seems to be added as a string, rather than going one level up, for example:

include(__DIR__ . "..\\another_folder\\file_2.php");

produces the following error:
Warning: include(C:\xampp\htdocs\main_folder..\another_folder\file_2.php) [function.include]: failed to open stream: No such file or directory in

Any idea what's going on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ぺ禁宫浮华殁 2025-01-12 12:34:38

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

include(__DIR__ . "\\..\\another_folder\\file_2.php");

这将使路径成为

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");

You need to add the \ after the directory name:

include(__DIR__ . "\\..\\another_folder\\file_2.php");

This will make the path be

C:\xampp\htdocs\main_folder\..\another_folder\file_2.php

instead of

C:\xampp\htdocs\main_folder..\another_folder\file_2.php

Also, for portability, it is advisable to use / instead of \, which works on all platforms, including Windows:

include(__DIR__ . "/../another_folder/file_2.php");
橘虞初梦 2025-01-12 12:34:38

不要在 PHP 的路径中使用反斜杠,而应在任何地方使用常规正斜杠 (/)。 PHP 会自动为您转换为适当的操作系统特定的目录分隔符。

话虽如此,详细查看错误消息:

 ... lude(C:\xampp\htdocs\main_folder..\another_folder\file_2.php) [func...
                                     ^--- missing a slash here

Don't use backslashes in paths in PHP, use regular forward slashes (/) everywhere. PHP will translate to the appropriate OS-specific directory separators for you automatically.

That being said, look at the error message in detail:

 ... lude(C:\xampp\htdocs\main_folder..\another_folder\file_2.php) [func...
                                     ^--- missing a slash here
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文