Php - get parent-script name

北城余情 提交于 2019-11-28 07:04:43

问题


parent.php:

require_once 'child.php';

child.php:

echo __FILE__;

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

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


回答1:


print $_SERVER["SCRIPT_FILENAME"];



回答2:


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



回答3:


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) ;-)




回答4:


Straight to the solution:

Parent Script:

echo $_SERVER['SCRIPT_FILENAME'];

Child Script (included file in parent script):

echo __FILE__;

Make a file called "parent.php" with contents:

include('child.php');

Make a file called "child.php" with contents:

echo "My Parent is at: " . $_SERVER['SCRIPT_FILENAME'] . "<br>";
echo "I'm at: " .  __FILE__;

You get the idea...




回答5:


You have to use basename($_SERVER["SCRIPT_FILENAME"]) or, if you like the script nam only, you can use basename($_SERVER["SCRIPT_FILENAME"], '.php').



来源:https://stackoverflow.com/questions/1318608/php-get-parent-script-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!