How can I find out which file includes the other in PHP?

3

I would like to know in PHP how I can find out which is the parent file, in an inclusion, through the child file.

Example:

  • avo.php
  • pai.php
  • hijo.php

In the avo.php file I have:

include_once 'pai.php';

And in the file pai.php I have:

#pai.php
include_once 'filho.php';
  • Through the filho.php file, how can I find out that it is included by pai.php ?
  • How can I find out, by filho.php , that pai.php is included by avo.php ?
asked by anonymous 04.08.2015 / 20:22

1 answer

3

Use debug_backtrace() or debug_print_backtrace , it can detect both include , require , include_once , require_once , and scope of functions and classes .

Using debug_backtrace() :

  • /foo/a.php file:

    <?php
    function a_test($str)
    {
        echo "\nOlá: $str";
        var_dump(debug_backtrace());
    }
    
    a_test('amigo');
    ?>
    
  • File /foo/b.php :

    <?php
    include_once '/foo/a.php';
    ?>
    
  • Result:

    Olá: amigo
    array(2) {
    [0]=>
    array(4) {
        ["file"] => string(10) "/foo/a.php"
        ["line"] => int(10)
        ["function"] => string(6) "a_test"
        ["args"]=>
        array(1) {
          [0] => &string(6) "amigo"
        }
    }
    [1]=>
    array(4) {
        ["file"] => string(10) "/foo/b.php"
        ["line"] => int(2)
        ["args"] =>
        array(1) {
          [0] => string(10) "/foo/a.php"
        }
        ["function"] => string(12) "include_once"
      }
    }
    

Using debug_print_backtrace :

  • File foo.php :

    <?php
    function a() {
        b();
    }
    
    function b() {
        c();
    }
    
    function c(){
        debug_print_backtrace();
    }
    
    a();
    ?>
    
  • index.php file :

    <?php
    include 'foo.php';
    ?>
    
  • Result:

    #0  c() called at [/foo.php:10]
    #1  b() called at [/foo.php:6]
    #2  a() called at [/foo.php:17]
    #3  include(/foo.php) called at [/index.php:3]
    
04.08.2015 / 20:34