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
I had this problem once, solved with:
if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false) ...
but the ideal solution is to place the file outside of the web-server document root, as mentioned in another anwser.
I have a file that I need to act differently when it's included vs when it's accessed directly (mainly a print()
vs return()
) Here's some modified code:
if(count(get_included_files()) ==1) exit("Direct access not permitted.");
The file being accessed is always an included file, hence the == 1.
The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above). You can still include them, but there is no possibility of someone accessing them through an http request.
I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.
if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) { die('Access denied'); };
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.
<?php
function a() {
// function body
}
function b() {
// function body
}
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.
system
, because that would conflict with a path used for code. I find this annoying.What you can also do is password protect the directory and keep all your php scripts in there, ofcourse except the index.php file, as at the time of include password won't be required as it will be required only for http access. what it will do is also provide you the option to access your scripts in case you want it as you will have password to access that directory. you will need to setup .htaccess file for the directory and a .htpasswd file to authenticate the user.
well, you can also use any of the solutions provided above in case you feel you don't need to access those files normally because you can always access them through cPanel etc.
Hope this helps