Check if a file was included or loaded

后端 未结 12 1214
轻奢々
轻奢々 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:59

    if (defined('FLAG_FROM_A_PARENT'))
    // Works in all scenarios but I personally dislike this
    
    if (__FILE__ == get_included_files()[0])
    // Doesn't work with PHP prepend unless calling [1] instead.
    
    if (__FILE__ == $_SERVER['SCRIPT_FILENAME'])
    // May break on Windows due to mixed DIRECTORY_SEPARATOR
    
    if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME']))
    // Doesn't work with files with the same basename but different paths
    
    if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME']))
    // Seems to do the trick as long as document root is properly configured
    

    Note: On WAMP Servers virtual-hosts sometimes inherit the default document root setting, causing $_SERVER['DOCUMENT_ROOT'] to display wrong path.

提交回复
热议问题