Php - get parent-script name

Max Frai picture Max Frai · Aug 23, 2009 · Viewed 11.4k times · Source

parent.php:

require_once 'child.php';

child.php:

echo __FILE__;

It will show '.../child.php'

How can i get '.../parent.php'

Answer

danorton picture danorton · Apr 15, 2011

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'];
}