Check if a file was included or loaded

后端 未结 12 1218
轻奢々
轻奢々 2020-12-08 13:35

Is there any elegant way to check if a file was included by using include/include_once/require/require_once or if the pag

12条回答
  •  半阙折子戏
    2020-12-08 13:58

    Quoted from: How to know if php script is called via require_once()?

    I was looking for a way to determine if a file have been included or called directly, all from within the file. At some point in my quest I passed through this thread. Checking various other threads on this and other sites and pages from the PHP manual I got enlightened and came up with this piece of code:

    if (basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])) {
      echo "called directly";
    } else {
      echo "included/required";
    }
    

    In essence it compares if the name of the current file (the one that could be included) is the same as the file that is beeing executed.

    Credit: @Interwebs Cowboy

提交回复
热议问题