Get name of file that is including a PHP script

本秂侑毒 提交于 2019-11-29 03:06:00

$_SERVER["PHP_SELF"]; returns what you want

zerkms

If you really need to know what file the current one has been included from - this is the solution:

$trace = debug_backtrace();

$from_index = false;
if (isset($trace[0])) {
    $file = basename($trace[0]['file']);

    if ($file == 'index.php') {
        $from_index = true;
    }
}

if ($from_index) {
    // Do something
} else {
    // Do something else
}

In case someone got here from search engine, the accepted answer will work only if the script is in server root directory, as PHP_SELF is filename with path relative to the server root. So the universal solution is

basename($_SERVER['PHP_SELF'])

Also keep in mind, that this returns the top script, for example if you have a script and include a file, and then in included file include another file and try this, you will get the name of the first script, not the second.

plague

In the code including list.php, before you include, you can set a variable called $this_page and then list.php can see the test for the value of $this_page and act accordingly.

PeeHaa

Perhaps you can do something like the following:

<ul>
    <?php
        $page_name = 'index';
        include("list.php")
    ?>
</ul>

list.php

<?php
    if ($pagename == 'index') {
        //Do something
    }
    else {
        //Do something
    }
?>

The solution basename($_SERVER['PHP_SELF']) works but I recommend to put a strtolower(basename($_SERVER['PHP_SELF'])) to check 'Index.php' or 'index.php' mistakes.

But if you want an alternative you can do:
<?php if (strtolower(basename($_SERVER['SCRIPT_FILENAME'], '.php')) === 'index'): ?>.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!