For example,
This is index.php
<?
require_once('header.php');
?>
Can header.php know it was included by index.php?
--EDIT--
I found a solution:
function backtrace_filename_includes($name){
$backtrace_array=debug_backtrace();
if (strpos($backtrace_array[1]['file'],$name)==false){
return false;
}else{
return true;
}
}
header.php
<?
if (backtrace_filename_includes('index.php')) echo "index.php";
?>
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.
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.
Edit: 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());
Output:
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
)
)
So while this works, you probably shouldn't use it. debug_backtrace
can be a noticeable performance drag when used excessively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With