Keith Maurino
Keith Maurino

Reputation: 3432

How to tell which PHP file was used to "include" another?

In PHP when using the include function is the a way to tell from the inserted file which file inserted you? For example, I use the following line often through my code:

include 'header.php';

Is there a way to tell from inside header.php what PHP file inserted you?

Upvotes: 1

Views: 513

Answers (5)

Paul Dixon
Paul Dixon

Reputation: 301075

One thing you can do is find the filename of the file which was used to handle the HTTP request. If all your includes are included directly from that script, you can find the full path to that requested script in $_SERVER["SCRIPT_FILENAME"]

You could also dig through a debug_backtrace() within the included code to determine which file included you, e.g.

$trace=debug_backtrace();

foreach($trace as $t)
{
    if (in_array($t['function'], 
                 array('include', 'include_once', 'require', 'require_once')))
    {
        echo 'Included from '.$t['file']."\n";
        break;
    }
}

Upvotes: 4

Gumbo
Gumbo

Reputation: 655707

debug_backtrace can tell you that.

Upvotes: 4

Mark Rushakoff
Mark Rushakoff

Reputation: 258418

The PHP manual lists the get_included_files function, which is sort of related to what you want... but one of the comments on that page says:

If you want to know which is the script that is including current script you can use $_SERVER['SCRIPT_FILENAME'] or any other similar server global.

Upvotes: 3

fbrereto
fbrereto

Reputation: 35935

While there's nothing builtin to the language, you could set up a coding pattern where a variable is set that tells you the source file doing the including:

$foo_php_old_includer = $includer;
$includer='foo.php';

include 'header.php'; // uses $includer to discern who is including it

// rest of source file

$includer=$foo_php_old_includer;

If every file had something like the above in it, you would create an "include stack" where each file would know which file included it.

All this being said I suspect the problem you are trying to solve might be better solved with a different methodology. If you could describe a bit the problem you are trying to solve with this method SO might be able to help you come up with a better solution.

Upvotes: 2

Fenton
Fenton

Reputation: 251232

You could set a variable for this, but it's not a perfect solution...

$CallingFile = 'myfile.php';
include 'header.php';

header.php can now interrogate the variable $CallingFile to know who called it.

Upvotes: 1

Related Questions