Protecting PHP Includes

One worry when you separate parts of your page out into individual files is having visitors to your site access those files directly and perhaps gain access to information that is not supposed to be available to visitors.

The best way to provide protection for your include files is to place them outside of the public folder of your web site. PHP can read files stored outside of your public site folder but web browsers can't access that information directly (which is why you can't use this to stop hotlinking to your images and Javascript). For anyone to access your include files directly there they would need access to your web server itself.

If you don't have access to store the includes outside of the public part of your site then the next best solution is to set up a password protected folderwithin your site and store the includes there. PHP can still access the include files but for anyone to access them directly they would need to know the password in order to gain entry into the folder.

If you don't have access to do even that then there are a couple of simple things that you can do to provide at least some protection for the content of your include file. The most obvious of these is to make sure that the include file has a php extension on the filename. This will ensure that the file will still get passed through the PHP processor before displaying in the browser which will at least stop people from seeing anything in the file source that doesn't get written out to the web page.

The second thing you can do is to add some code to the top of the file that tests if the file is being accessed directly rather than being included into another PHP page and which then displays an error message rather than running the actual code within the file. We can even write this code such that it doesn't matter what we call the include file and what we call the other files that we may want to include this one. The following code added to the top of the include file will prevent its being accessed directly while still allowing it to be included into any of the other PHP scripts that you have on your site.

if(eregi(basename(__FILE__),$_SERVER['REQUEST_URI']))
die('Direct access prohibited');

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate