包含的PHP文件可以知道包含它的位置吗? [英] Can an included PHP file know where it was included from?
问题描述
例如,
这是index.php
This is index.php
<?
require_once('header.php');
?>
header.php可以知道它是否包含在index.php中吗?
Can header.php know it was included by index.php?
-编辑-
我找到了解决方法:
function backtrace_filename_includes($name){
$backtrace_array=debug_backtrace();
if (strpos($backtrace_array[1]['file'],$name)==false){
return false;
}else{
return true;
}
}
header.php
header.php
<?
if (backtrace_filename_includes('index.php')) echo "index.php";
?>
推荐答案
$_SERVER['PHP_SELF']
将包含当前正在执行的脚本,无法从包含的文件中确定哪个特定的脚本导致了包含.
While $_SERVER['PHP_SELF']
will contain the currently executing script, there is no way to determine from an included file which specific script caused the include.
这意味着,如果a.php
包括b.php
,其中包括c.php
,则c.php
将无法知道b.php
是包含者.最好的结果是a.php
是当前正在执行的脚本.
This means that if a.php
includes b.php
, which includes c.php
, c.php
will have no way of knowing that b.php
was the includer. The best you can get is that a.php
is the currently executing script.
是的,我上面的答案在技术上是错误的-您可以使用 debug_backtrace
查找调用方,即使没有功能也要直到PHP 5.4删除该功能.
Yup, my above answer is technically wrong -- you can use debug_backtrace
to find the caller, even without functions, up until PHP 5.4, which removes this functionality.
a.php:
<?php
echo 'A';
include 'b.php';
b.php:
<?php
echo 'B';
include 'c.php';
c.php:
<?php
echo 'C';
print_r(debug_backtrace());
输出:
ABCArray
(
[0] => Array
(
[file] => /tmp/b.php
[line] => 3
[function] => include
)
[1] => Array
(
[file] => /tmp/a.php
[line] => 3
[args] => Array
(
[0] => /tmp/b.php
)
[function] => include
)
)
因此,尽管此方法有效,但您可能不应该使用它.过度使用 debug_backtrace
可能会明显降低性能.
So while this works, you probably shouldn't use it. debug_backtrace
can be a noticeable performance drag when used excessively.
这篇关于包含的PHP文件可以知道包含它的位置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!