7

when on "index.php", I do require_once("/all_fns.php").

"all_fns.php" itself requires files with paths relative to all_fns.php (itself).

My question is, should I write the paths on all_fns relative to all_fns.php or to index.php?

This is all very confusing to me and wanted to get it straight.

Gal
  • 23,122
  • 32
  • 97
  • 118
  • As a side note, "/all_fns.php" is an *absolute* path that will look for a file in the OS's root directory (on a non-Windows system) – Powerlord Dec 23 '09 at 19:42
  • On a Windows system as well. It will search in the current drive's root. – Pekka Dec 23 '09 at 20:19

4 Answers4

14

They are treated as relative to index.php.

If you need to reference a file relative to the include, use

__DIR__."/relative/file.php";
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • This worked for me when I wanted a relative path. require_once('../bla.php'); would not work. require_once(\_\_DIR\_\_.'/../bla.php'); works. – Benbob Sep 29 '10 at 01:09
  • 1
    @AlixAxel `dirname(__FILE__)` is needed on older PHP versions. – nanofarad Jun 29 '12 at 12:57
  • @ObsessiveFOSS: Yes, but the OP hasn't stated that he's using a *very* old PHP version, we can assume that he's using the latest stable release. – Alix Axel Jun 30 '12 at 00:05
  • 1
    @AlixAxel so newest version is assumed? – nanofarad Jun 30 '12 at 17:22
  • @ObsessiveFOSS: Not the newest, but the latest stable one (give or take 6 months for server packages to catch up - https://launchpad.net/ubuntu/+source/php5), `__DIR__` was stable since 30-Jun-2009. Either way, the answer and the comment still provide both options, I just think we shouldn't be advocating prehistoric code. But then again, SourceForge kept supporting PHP 3.X for a terribly long time. – Alix Axel Jun 30 '12 at 17:45
2

They are relative to the getcwd().

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
0

in index.php define some directories

define ( 'INCLUDES_DIR', dirname( __FILE__ ) );
define ( 'INCLUDES_DIR2', INCLUDES_DIR . '/some_directory' );

then in all the other files you can use INCLUDES_DIR

include( INCLUDES_DIR1 . 'file.php' );
Galen
  • 29,976
  • 9
  • 71
  • 89
0

Either Use

echo  in_get( "include_path") ;

Or open up your ini file and find out what your ini path is, and put your include file in THAT DIRECTORY (or one of those directories) and release yourself from worrying about absolute/relative include problems forever.

Cups
  • 6,901
  • 3
  • 26
  • 30