Search code examples
phpfileinclude

PHP: Check if a file is loaded directly instead of including?


Is there a way to prevent a user viewing an file but still use it as included to another file in PHP?


Solution

  • If you use

    define('APP_RAN'); 
    

    in the file that includes it and then put

    if(!defined('APP_RAN')){ die(); }
    

    or alternatively

    defined('APP_RAN') or die();
    

    (which is easier to read)

    in included files it would die if you access them directly.


    It would probably be better to put all of your included files above your DocumentRoot though.

    For example, if your index page is at

    /my/server/domain/public_html
    

    You should put the included files in

    /my/server/domain/