A. L
A. L

Reputation: 12689

Way to get absolute path of file PHP

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.

Upvotes: 28

Views: 130045

Answers (3)

WEBjuju
WEBjuju

Reputation: 6591

__FILE__

That is the absolute path to the file being executed.

simple usage examples:

echo __FILE__;

echo "This file is: " . __FILE__;

Upvotes: 17

Anik Anwar
Anik Anwar

Reputation: 805

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

$path = new SplFileInfo(__FILE__);
echo 'The real path is '.$path->getRealPath();

Upvotes: 2

S.I.
S.I.

Reputation: 3375

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";

Upvotes: 58

Related Questions