6

I am using a php library which has this code: require_once dirname(__FILE__) . '/config.php';

From what I've read, dirname(__FILE__) points to the current directory.

So wouldn't it be easier to just write require_once 'config.php';?

My only guess here is that including the dirname(__FILE__) ensures that the require_once function uses an absolute rather than relative path.

Leo Galleguillos
  • 2,429
  • 3
  • 25
  • 43
  • 1
    That's the reason - it ensures an absolute path. Other scripts can change the working directory with `chdir()`, which can confuse the include paths. Likewise, if called from something other than HTTP (like CLI or cron, for example), the include paths may be different, or the working directory may be different. – Michael Berkowski Jan 15 '14 at 21:15
  • 3
    Could just use `__DIR__` instead... – Niet the Dark Absol Jan 15 '14 at 21:18
  • Aparently `__DIR__` is available from php 5.3 and up. Sources:[1](http://stackoverflow.com/a/29423749/3258851), [2](http://stackoverflow.com/a/2749423/3258851) – Marc.2377 Oct 07 '16 at 10:43

2 Answers2

8

Yes, you are right - dirname(__FILE__) ensures that the require_once function uses an absolute rather than relative path.

The __FILE__ constant represents the running script. It will return the full path and file name of the running script.

For example, if a script called database.init.php which is included from anywhere on the filesystem wants to include the script database.class.php, which lays in the same directory, you can use:

require_once dirname(__FILE__) . '/database.class.php'; 
mate64
  • 9,876
  • 17
  • 64
  • 96
1

an example:

if your file is inlcuded somewhere then by default it will start searching from the path of the file that included yours. in this case the require will not work for files that are next to your file