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

17,762

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

Solution 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
Share:
17,762
mickael
Author by

mickael

Updated on June 04, 2022

Comments

  • mickael
    mickael almost 2 years

    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?

  • mickael
    mickael about 12 years
    Thank you for both tips! I was wondering about portability as well... Cheers man!
  • mickael
    mickael about 12 years
    Thank you!, I thought the last slash was not important as the idea was to go up one folder and then down again to 'another_folder'. Working now!
  • James Bond
    James Bond about 4 years
    __DIR__ . '../dir' fixed the bug behavior on Windows 10)