28

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.

3
  • Possibly duplicate of stackoverflow.com/questions/3952590/… Commented Nov 3, 2016 at 5:36
  • try this echo $_SERVER["DOCUMENT_ROOT"]; Commented Nov 3, 2016 at 5:38
  • @SuperCoolHandsomeGelBoy No, that only gives me up to /var/www/html. My file is nested within a couple more folders in. Commented Nov 3, 2016 at 5:40

3 Answers 3

59

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

2 Comments

+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).
for some strange reason $rootDir = realpath($_SERVER["DOCUMENT_ROOT"] .'/../yourfile.php' ); will not work
17

__FILE__

That is the absolute path to the file being executed.

simple usage examples:

echo __FILE__;

echo "This file is: " . __FILE__;

1 Comment

This is simpler and easy to remember
2

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

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

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.