Get filename of file which ran PHP include

Solution 1:

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.

Solution 2:

$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.