Get filename of file which ran PHP include

2019-01-09 03:28发布

When using the PHP include, how can I find out which file is calling the include? In short, what is the parent's file filename?

标签: php include
4条回答
该账号已被封号
2楼-- · 2019-01-09 04:10
$fileList = get_included_files();
$topMost = $fileList[0];
if ($topMost == __FILE__) echo 'no parents';
else echo "parent is $topMost";

I think this should give the right result when there's a single parent.

By that I mean the situation where the parent is not a required or an included file itself.

查看更多
女痞
3楼-- · 2019-01-09 04:20

An easy way is to assign a variable in the parent file (before the inclue), then reference that variable in the included file.

Parent File:

$myvar_not_replicated = __FILE__; // Make sure nothing else is going to overwrite
include 'other_file.php';

Included File:

if (isset($myvar_not_replicated)) echo "{$myvar_not_replicated} included me";
else echo "Unknown file included me";

You could also mess around with get_included_files() or debug_backtrace() and find the event when and where the file got included, but that can get a little messy and complicated.

查看更多
叼着烟拽天下
4楼-- · 2019-01-09 04:22

In the parent file, add this line before including the child file:

$_SESSION['parent_file'] = $_SERVER['PHP_SELF'];

And then in the child file, read the session variable:

$parent_file = $_SESSION['parent_file']
查看更多
对你真心纯属浪费
5楼-- · 2019-01-09 04:27

Late answer, but ...

I check the running parent filename by using:

$_SERVER["SCRIPT_NAME"] // or 
$_SERVER["REQUEST_URI"] // (with query string)
查看更多
登录 后发表回答