RobbieGee
RobbieGee

Reputation: 1591

Can I get the path of the PHP file originally called within an included file?

Let's say we have index.php and it is stored in /home/user/public/www and index.php calls the class Foo->bar() from the file inc/app/Foo.class.php.

I'd like the bar function in the Foo class to get a hold of the path /home/user/public/www in this instance — I don't want to use a global variable, pass a variable, etc.

Upvotes: 3

Views: 15556

Answers (4)

Philip Reynolds
Philip Reynolds

Reputation: 9392

getcwd() gets the current working directory

It can be changed for a variety of reasons by 3rd party modules, includes or even your own code by issuing a chdir().

debug_backtrace() as Devon suggested is the answer you're looking for.

Upvotes: 2

Paul Dixon
Paul Dixon

Reputation: 300845

Wouldn't this get you the directory of the running script more easily?

$dir=dirname($_SERVER["SCRIPT_FILENAME"])

Upvotes: 12

Devon
Devon

Reputation: 5784

You can use debug_backtrace to look at the calling path and get the file calling this function.

A short example:

class Foo {
  function bar() {    
   $trace = debug_backtrace();
   echo "calling file was ".$trace[0]['file']."\n";
  }
}

Upvotes: 15

RobbieGee
RobbieGee

Reputation: 1591

Found it. getcwd().

Upvotes: 1

Related Questions