PHP Security - Specifics

Prevent Includes Running Separately

One way of modularising your PHP so that you can share code between web pages is to use include or require statements to incorporate other files into the page. Usually each of these other files will provide some part of either the HTML to be output in the page or common functionality called from elsewhere in the page (or both).

In almost every case these files will only be providing a part of a web page and so ought not to be able to be loaded separately. There are two ways that we can prevent these files from being able to be run separately. One way is to simply move the files above the folder that is accessible from the web so that they cannot be loaded separately regardless of what the visitors to our site try to do.

Not everyone has access to locate their include files that way though. Fortunately there is an alternative solution that can be easily applied to any include file without having to modify anything except the include file itself.

Simply add the following code to the top of all your PHP include modules and it will no longer be possible for the code in them to be run directly. Any attempt to run the file directly will mean that the condition in this extra if statement added to the top of your code is satisfied and none of the rest of the code in the include will be run.

$file = basename(__FILE__);
{die('This file cannot be accessed directly!');}


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow