peter70
peter70

Reputation: 1113

php include path on windows

I work with PHP on Windows, sience a few days. The whole time I've been indicated include in the following manner:

In index.php file:

require ('include/init.inc');

In the directory "include" I stated:

In init.inc file:

require ("workbench.inc"); 

But suddenly no longer works. At one time I must also in "init.inc" specify the directory. Why did it all the time to work, and suddenly no more?

Upvotes: 2

Views: 4450

Answers (1)

Lumen
Lumen

Reputation: 3574

From the PHP documentation:

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing

So the current working directory (CWD) is important when including other files. It can be retrieved by getcwd().

If your directory structure looks like this

rootdir/
    include/
        init.rc
        workbench.rc
    index.php

then a require('include/init.rc') will only work if rootdir/ is the CWD or is part of the search path. Likewise, require('init.inc') assumes the CWD is rootdir/include/. Since the current working directory can change, it is idomatic in PHP to use the more robust

// in index.php
require(__DIR__ . '/include/init.rc');

// in workbench.rc
require(__DIR__ . '/init.rc');

Then the require will work independent of the CWD. This works because the magic constant __DIR__ is replaced by the absolute path to the file that contains the constant without a trailing directory separator, for example

  • in index.php, __DIR__ is D:\path\to\rootdir and
  • in include/init.rc, __DIR__ is D:\path\to\rootdir\include.

Upvotes: 3

Related Questions