【问题标题】:PHP - include() or require() with relative paths won't work on windows, even when appending __DIR__PHP - 具有相对路径的 include() 或 require() 在 Windows 上不起作用,即使附加 __DIR__
【发布时间】:2012-03-07 07:47:44
【问题描述】:

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

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

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

产生以下错误: 警告:include(C:\xampp\htdocs\main_folder..\another_folder\file_2.php) [function.include]:打开流失败:

中没有这样的文件或目录

知道发生了什么吗?

【问题讨论】:

    标签: php include relative-path require


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢!,我认为最后一个斜杠并不重要,因为我的想法是先上一个文件夹,然后再下到“another_folder”。现在工作!
    【解决方案2】:

    需要在目录名后面加上\

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

    【讨论】:

    • 感谢您的两个提示!我也想知道便携性......干杯人!
    • __DIR__ . '../dir' 修复了 Windows 10 上的错误行为)
    猜你喜欢
    • 2010-12-29
    • 1970-01-01
    • 2011-06-08
    • 2017-03-14
    • 2014-06-25
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多