Viewed   81 times

I'm having trouble understanding the ruleset regarding PHP relative include paths. If I run file A.PHP- and file A.PHP includes file B.PHP which includes file C.PHP, should the relative path to C.PHP be in relation to the location of B.PHP, or to the location of A.PHP? That is, does it matter which file the include is called from, or only what the current working directory is- and what determines the current working directory?



It's relative to the main script, in this case A.php. Remember that include() just inserts code into the currently running script.

That is, does it matter which file the include is called from


If you want to make it matter, and do an include relative to B.php, use the __FILE__ constant (or __DIR__ since PHP 5.2 IIRC) which will always point to the literal current file that the line of code is located in.

Sunday, December 4, 2022

There are two types of paths: relative, and absolute. Absolute paths start with a /.. (or C:/.. or however that works on Windows) and always unequivocally point at one specific file.

Relative paths (not starting with /) are relative to the include_path variable. That's a variable that contains a bunch of folders, where PHP will look for your relative path. That include_path also includes ., the current directory. The "current" directory depends on which file was the "first" to be executed. So it varies depending on which file starts to include others.

  1. You can set your include_path to some specific, unchanging directory, so you always have a fixed path to include to relatively.
  2. Better: construct absolute paths:

    include __DIR__ . '/../Login/file.php';

    This is always relative to the directory the file is in.

Tuesday, October 11, 2022

You need to add the after the directory name:

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

This will make the path be


instead of


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

include(__DIR__ . "/../another_folder/file_2.php");
Monday, October 10, 2022

You can't include php files relatively to your webroot that way, cause if you use the slash as first character, the reference will go much deeper than just your document root. So, instead of using your basepath, you could do something like this :

   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/yourpath/yourfile.php";
Friday, August 12, 2022

I'm not sure what all you're doing, but since somefile.txt is in the same folder as, you could make the path to it relative to the module by using its predefined __file__ attribute:

import os
fileToRead = os.path.join(os.path.dirname(__file__), "somefile.txt")
Thursday, November 24, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :