2

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?

3
  • You have to be a bit more explicit. Are you using PHP with Apache or on CLI? What is your directory structure? Commented Dec 26, 2015 at 13:39
  • I work with Eclipse and use XDebug. The Application is configured and it's runnig as an CLI Application, but I have installed wamp also and the wamp Server is still running. The dir stucture is very simple. I have a root and an include dir. Commented Dec 26, 2015 at 15:02
  • When I put the code into "include/init.inc": set_include_path(get_include_path() . PATH_SEPARATOR . 'D:\...my path ...\include'); then it works fine. But until todayit was not necessary... Commented Dec 26, 2015 at 15:16

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.