PHP - include() or require() with relative paths won't work on windows, even when appending __DIR__

走远了吗. 提交于 2019-12-10 10:09:05

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/9302364/php-include-or-require-with-relative-paths-wont-work-on-windows-even-whe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!