I have a log() method and want to log the name of the script that called it. How is that possible in PHP?
5 Answers
Depending on the calling environment, you should have a look at debug_backtrace, and $_SERVER['PHP_SELF']
debug_backtrace()
will give you a stack trace of the includes and function calls so far, and $_SERVER['PHP_SELF']
will tell you the currently executing script, which is easier and might work just as well for what you want. $_SERVER['PHP_SELF']
will pretty much always be the script that was called from the browser, for example, if you had blah.com/admin.php
and blah.com/articles.php
that both called /pages.php
to get a list of the pages saved in a blog or something, and something went wrong -- the log would tell you whether admin.php
or articles.php
was calling the script. But if pages.php
included functions.php
which included libs.php
and libs.php failed, and you wanted to know that functions.php
included it, this wouldn't work -- the log would still show the script that started the including (admin.php
or articles.php
). In this case you would use debug_backtrace()
.

- 37,678
- 39
- 126
- 176
You can take a look at the debug_backtrace
function : in it's output, you should find what you are looking for ;-)
You can take a look to this answer I posted a couple of days ago, for more informations, and an example.

- 1
- 1

- 395,085
- 80
- 655
- 663
-
look at all the 'informations' in that link! I'm digging informations! lol – pythonian29033 Nov 23 '16 at 09:15
Take a look at debug_baktrace.
$backtrace = debug_backtrace();
print_r($backtrace[1]);

- 18,838
- 2
- 61
- 93
Use debug_backtrace() to get an associative array containing the complete callstack and examine the array to pull the details you're interested from it.

- 159,146
- 25
- 197
- 199
In addition to the answers already given a very low-tech answer would be to or append _ _ FILE _ _ or basename() to a string which is being logged. (had to add spaces to double underscore in FILE to make it display)

- 6,901
- 3
- 26
- 30