Prevent direct access to a php include file

后端 未结 30 1366
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:32

I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it\'s accessed directly by typing

30条回答
  •  孤城傲影
    2020-11-22 06:58

    I found this php-only and invariable solution which works both with http and cli :

    Define a function :

    function forbidDirectAccess($file) {
        $self = getcwd()."/".trim($_SERVER["PHP_SELF"], "/");
        (substr_compare($file, $self, -strlen($self)) != 0) or die('Restricted access');
    }
    

    Call the function in the file you want to prevent direct access to :

    forbidDirectAccess(__FILE__);
    

    Most of the solutions given above to this question do not work in Cli mode.

提交回复
热议问题