How to detect if a file is being included or directly ran

前端 未结 6 980
春和景丽
春和景丽 2021-01-20 00:09

I have a php file that I include in my php script, but I don\'t want people to be able to directly run the file(without being included). How can I prevent that from happenin

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-20 00:51

    Checking if the script is the parent of the PHP process might not be the best idea for preventing users of requesting an include file directly. But it can be handy in many other cases i.e. AJAX modules etc. I'm not gonna start a new topic by this.

    if (__FILE__ == get_included_files()[0])
    // Doesn't work with PHP prepend unless calling [1] instead.
    
    if (__FILE__ == $_SERVER['DOCUMENT_ROOT'] . $_SERVER['SCRIPT_FILENAME'])
    // May not work on Windows due to mixed DIRECTORY_SEPARATOR (machine specific)
    
    if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME']))
    // Doesn't work with files with the same basename but different paths
    
    if (defined('FLAG_FROM_A_PARENT'))
    // Works in all scenarios but I personally dislike this
    
    if (realpath(__FILE__) == realpath($_SERVER['DOCUMENT_ROOT'] . $_SERVER['SCRIPT_FILENAME']))
    // Should work flawlessly
    

    Keep in mind some machines that use virtual paths may return different paths in different php components. realpath() is your friend for this.

提交回复
热议问题