Php - get parent-script name

The chosen answer only works in environments that set server variables and specifically won’t work from a CLI script. Furthermore, it doesn't determine the parent, but only the topmost script file.

You can do almost the same thing from a CLI script by looking at $argv[0], but that doesn’t provide the full path.

The environment-independent solution uses debug_backtrace:

function get_topmost_script() {
  $backtrace = debug_backtrace(
      defined("DEBUG_BACKTRACE_IGNORE_ARGS")
      ? DEBUG_BACKTRACE_IGNORE_ARGS
      : FALSE);
  $top_frame = array_pop($backtrace);
  return $top_frame['file'];
}

print $_SERVER["SCRIPT_FILENAME"];

I don't think you can do that : the __FILE__ magic constant indicates in which file it is written ; and that is all.

If you want to know which PHP script was initially called (which URL was requested, for instance), you might have more luck looking at the $_SERVER superglobal : it contains many informations, including some that will help you (like SCRIPT_FILENAME or SCRIPT_NAME, for instance) ;-)

Tags:

Php

Parent