Prevent direct access to a php include file

后端 未结 30 1010
盖世英雄少女心
盖世英雄少女心 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 07:15

    Storing your include files outside the web accessible directory has been mentioned a few times, and is certainly a good strategy where possible. However, another option I have not yet seen mentioned: ensure that your include files don’t contain any runnable code. If your include files merely define functions and classes, and have no code other than that, they will simply produce a blank page when accessed directly.

    By all means allow direct access to this file from the browser: it won’t do anything. It defines some functions, but none of them are called, so none of them run.

    The same applies to files which contain only PHP classes, and nothing else.


    It’s still a good idea to keep your files outside of the web directory where possible.

    • You might accidentally deactivate PHP, in which case your server may send content of the PHP files to the browser, instead of running PHP and sending the result. This could result in your code (including database passwords, API keys, etc.) leaking.
    • Files in the web directory are squatting on URLs you may want to use for your app. I work with a CMS which cannot have a page called system, because that would conflict with a path used for code. I find this annoying.

提交回复
热议问题