There are times when you need to prevent direct file access to a PHP file. I’m talking about a file a web browser can display just by entering the full URL in the address bar. If the file does some type of processing that it shouldn’t do as a stand alone file, you need a way to prevent it from processing as a stand alone fine . While you can’t stop it from being displayed if the file is anywhere in your web directory tree, you can make sure it can’t do anything other than display a blank screen.
Prevent Direct File Access to Included Files
If you have PHP files that need to be included (or required), a simple routine at the beginning of the file will prevent it from being displayed in a web browser. I’m sure there are other ways to do it, but this way is pretty simple and it works. (I use the PHP realpath function to make sure the correct path is always being used):
if (realpath(__FILE__) === realpath($_SERVER["SCRIPT_FILENAME"])) exit;
You may be tempted to use something like this to prevent direct file access to PHP files used with AJAX routines but it won’t work. Those files need to be accessed just like a web browser would get access to them.
Preventing Direct File Access to other PHP Files
There are several ways to prevent direct file access to other PHP files (other than included/required files), but it’s really easy using sessions. If you set a session variable in the main script and then check for its existence in the script being called (even with AJAX post routines), you can tell the script to exit if the session variable doesn’t exist (or is wrong). Something like this at the top of the script would work:
if (!isset($_SESSION['something']) || $_SESSION['something'] != $correct_data) exit;
If you use an AJAX “get” routine, you can set a variable to be checked:
if (!isset($_GET['something') || $_GET['something'] != $correct_data) exit;
Hiding Pure Data Files
While it’s not quite same thing, PHP can be used to prevent direct file access to pure data files. You set up a data file as a comment, which PHP won’t process, and save it with the “.php” extension:
this little piggy went to the market
this little piggy went home
When you’re writing the data, you have to remember to write out the PHP code to be saved with the data file.
All of this can be avoided by using the proper directory/file permissions, setting up indexes the right way and by putting scripts outside of the web directory tree. Of course, your options may be limited and you may not be able to control all aspects of development or usage by other parties. In cases like that, routines like these may be the only way to protect your files and data.
If your code can’t return an HTTP error to a web browser when visitors are trying to do something they shouldn’t be doing, the next best thing is to give them a blank screen.