6

DIR is a magic constant as stated in the PHP docs. getcwd() is just the current working directory according to the PHP docs.

My use case is:

// this is my index.php file
require_once __DIR__ . '/vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->get('/{name}', function($name) use($app) {
    return $app->sendFile(__DIR__ . '/web/source/index.php');
});

I don't fully understand why I need either of these mechanisms as I should just be able to use relative paths.

However the code fails with out it.

Zen-Lee Chai
  • 431
  • 1
  • 4
  • 10
  • \_\_DIR\_\_ relates to the directory of the current php file; getcwd() is the current working directory.... you can include files from outside of the directory where PHP is executing, or you can change the directory where PHP is executing – Mark Baker Jul 14 '15 at 13:27

2 Answers2

9

__DIR__ is where the currently executing file is.

getcwd() is the current directory php file is executing from. Remember you are on the server and not the client and need to be mindful of what directory you are working from.

This can change.

See here for more on this concept.

  • If you are running the script from the same location, getcwd() and __DIR__ will be the same. __DIR__ would be a bit faster though as it does not call a function. – Wouter Jan 21 '19 at 13:39
8

Let's assume you have the script

<?php
echo __DIR__, ' | ', getcwd();
include 'subdir/foo.php';

and it gets executed as the main script (because of a browser request or it's the main script for php-cli call).
And subdir/foo.php is the same except for the include.

The output for the main script might be something like

/path | /path

but the output for subdir/foo.php when included by the main script will be

/path/subdir | /path

__DIR__ reflects the directory in which the current script file resides.
But include() didn't change the current working directory, so the output of getcwd() remains /path.

VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • Cool, but how am I suppose to know what changes the cwd(current working directory). – Zen-Lee Chai Jul 14 '15 at 14:08
  • chdir() does - but stay away from it (unless you have no choice and know exactly what you're doing). If I were your code reviewer you'd have to hard time making a case for anything cwd related in a webserver project (....don't know if I could hold that position though, strong opinion weakly held :-) ) – VolkerK Jul 14 '15 at 14:19