Let’s say we have a PHP script that we don’t want users to access directly by calling it through their browser. We want that script to be included in other scripts but not accessed by typing its URL.
A lot of sites suggest saving such scripts into a directory outside the document root. This would do, but in some cases might not be an optimal solution. For example, you might need to be able to easily distribute your PHP application in an archive that the user can easily extract into some folder on his site. Telling your users to move some files to a folder outside their web root adds a lot of inconvenience and confusion. And you’ll probably add a lot of support overhead due to this approach.
Another method I prefer is to add code at the top of the script that checks if it is included in another file or being accessed directly. A good way of doing this is using the get_included_files PHP function. Here is what I use at the top of any such scripts:
<?php $inc = get_included_files(); if(basename(__FILE__) == basename($inc)) exit();
The first item in the array returned by get_included_files is the path of the script called directly by the user. The following items in the array are any other scripts that were included afterwards. So, the above line of code makes sure the current script is not the first item in that array.