Yevgeny Simkin
Yevgeny Simkin

Reputation: 28349

Is there a way to get the name of the top level PHP file from inside an included one?

Let's say I'm writing a global logData method that wants to write to a log file that has the same name as the php that's running it, but with a .log extension.

I'm including this logging in a parent php with the intention of having it always write to log files that are whatever the *parent file name is (not the tools.php lib in which it's sitting).

So, I have /some/arbitrary/directory/parent.php

which calls

include ("/path/to/my/php/libs/tools.php");

but when I run my logging method that's in tools.php it logs to a file called

/path/to/my/php/libs/tools.php.log

rather than /some/arbitrary/directory/parent.php.log (which is what I'd like).

I'm using __FILE__ which is behaving this way (probably as its intended to). Is there a command for getting the parent's file name so that I can get this to work as I intend? Or will I have to pass FILE as a param into my method from the parent php to get it to write to the correct output file?

TIA

Upvotes: 1

Views: 500

Answers (3)

Lawrence Barsanti
Lawrence Barsanti

Reputation: 33232

You could probably use $_SERVER["SCRIPT_FILENAME"]

Upvotes: 5

xdazz
xdazz

Reputation: 160833

You need to pass __FILE__ to the log class.

Something like:

// file:/some/arbitrary/directory/parent.php
$logger = new Logger(__FILE__);


// file:/path/to/my/php/libs/tools.ph
public function __construct($file) {
  // But it is not good idea to save log file same with php files.
  $this->log_path = $file.'.log';
}

Upvotes: 0

Robbie
Robbie

Reputation: 17710

debug_backtrace() will give you what you need.

http://php.net/manual/en/function.debug-backtrace.php

Upvotes: 2

Related Questions