Search code examples
phprequire-once

Is there a way to find out which FILE used require_once?


Let's say I have the following situation:

File1.php:

<?php
require_once('init.php');
...
?>

File2.php:

<?php
require_once('init.php');
...
?>

init.php:

<?php
magic_function_which_tells_me_which_file_parsed_this_file();
...
?>

I know this is a long-shot, but is there a way to know from within init.php which file included init.php it in the current execution?


Solution

  • You are able to use debug_backtrace to find the caller even without functions:

    test1.php

    <?php
    echo 'test1';
    include 'test2.php';
    

    test2.php

    <?php
    echo 'test2';
    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
        )
    )
    

    Anyways, I'd not recommend using it because it can be a noticeable performance drag when used excessively.