Get filename of file which ran PHP include

后端 未结 7 2049
后悔当初
后悔当初 2020-11-28 11:47

When using the PHP include, how can I find out which file is calling the include? In short, what is the parent\'s file filename?

相关标签:
7条回答
  • 2020-11-28 12:24
    $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.

    0 讨论(0)
  • 2020-11-28 12:25

    I was searching same information on web for complement my online course about php and found two ways. The first was

    $file = baseline($_SERVER['PHP_SELF']);
    echo $file;  //that outputs file name
    

    BUT, in include or require cases it gets the final file that it's included or required. Also found this, the second

    $file = __FILE__;
    echo $file; //that outputs the absolute way from file
    

    BUT i just was looking for the file name. So... I mix it up and it worths well!

    $file = basename(__FILE__);
    echo $file; //that outputs the file name itself (no include/require problems)
    
    0 讨论(0)
  • 2020-11-28 12:31

    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.

    0 讨论(0)
  • 2020-11-28 12:35

    You could use debug_backtrace() directly with no additional changes from within the included file:

    $including_filename = pathinfo(debug_backtrace()[0]['file'])['basename'];
    

    This will give you the name of the file that's including you.

    To see everything you have access to from within the included file, run this from within it:

    print_r(debug_backtrace());
    

    You will get something like:

    Array
    (
        [0] => Array
            (
                [file] => /var/folder/folder/folder/file.php
                [line] => 554
                [function] => include
            )
    
    )
    
    0 讨论(0)
  • 2020-11-28 12:37

    Late answer, but ...

    I check the running parent filename by using:

    $_SERVER["SCRIPT_NAME"] // or 
    $_SERVER["REQUEST_URI"] // (with query string)
    
    0 讨论(0)
  • 2020-11-28 12:37

    Got this from here: https://stackoverflow.com/a/35622743/9270227

    echo "Parent full URL: ";
    echo $_SERVER["SCRIPT_FILENAME"] . '<br>';
    
    0 讨论(0)
提交回复
热议问题