22

Is there a way to get the absolute path of a file while having it included in another script?

So I'm trying to include a file that's in folder A while I'm in folder B but it keeps trying to refer to folder B's location.

I've tried dirname, $SERVER['PHP_SELF'], cwd(), but they still return a relative path.

A. L
  • 11,695
  • 23
  • 85
  • 163
  • Possibly duplicate of http://stackoverflow.com/questions/3952590/php-how-to-find-application-root –  Nov 03 '16 at 05:36
  • try this echo $_SERVER["DOCUMENT_ROOT"]; – JYoThI Nov 03 '16 at 05:38
  • @SuperCoolHandsomeGelBoy No, that only gives me up to `/var/www/html`. My file is nested within a couple more folders in. – A. L Nov 03 '16 at 05:40

3 Answers3

51

You can try like this

include dirname(__FILE__).'/../yourfile.php';

Since PHP 5.3.0 you can use also the magic constant __DIR__ More info in the docs

Another way is

$rootDir = realpath($_SERVER["DOCUMENT_ROOT"]);

include "$rootDir/yourfile.php";
S.I.
  • 3,250
  • 12
  • 48
  • 77
  • 1
    +1 for the options! that made me think of this (common?) line: `$base_dr = basename(__DIR__);` (where the directory at the top of the structure drives biz logic somehow). – WEBjuju Jul 26 '18 at 15:19
  • for some strange reason `$rootDir = realpath($_SERVER["DOCUMENT_ROOT"] .'/../yourfile.php' );` will not work –  Sep 27 '21 at 12:13
16

__FILE__

That is the absolute path to the file being executed.

simple usage examples:

echo __FILE__;

echo "This file is: " . __FILE__;

WEBjuju
  • 5,797
  • 4
  • 27
  • 36
2

If you need the real path you can use the SplFileInfo.

$path = new SplFileInfo(__FILE__);
echo 'The real path is '.$path->getRealPath();
Anik Anwar
  • 625
  • 5
  • 11