Over a million developers have joined DZone.

PHP Security - Block Access to Include Files Using .htaccess

DZone's Guide to

PHP Security - Block Access to Include Files Using .htaccess

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

When I build websites for clients and myself, I use numerous include files to make my website easy to maintain. These include files may:

  • be composed of pure HTML; no server-side programming involved
  • be PHP class files; used throughout the website
  • composed of both HTML and PHP
  • PHP code to produce a specific action; many times, AJAX scripts

Obviously, if a person were to get lucky and guess the path and file name of my include scripts, problems could result, especially if an AJAX script is not secured (but I wouldn't do that — nor would you, right?). For example, take the following poorly coded bit of PHP that would get run when an AJAX call was made:

//inside file:   includes/ajax/delete_id.inc
$query = 'DELETE FROM my_table WHERE id = '.$_GET['id'];

Imagine if the user changed the 'id' in the querystring to "' or 1" — all data would be lost! (There's really no excuse for having an unprotected script, but this is a simple example)

Even if my scripts are secure (meaning I use proper validation to make sure they've been called correctly), a user/hacker has no business calling an include file. Using .htaccess, we can prevent any attempt by a user to reach an include file:

<FILES ~ "\.inc$">
Order allow,deny
Deny from all

The above code tells the server to disallow any requests by the user for any file ending in ".inc". You can easily modify the above .htaccess for your own naming convention and folder structure.

Do you employ this type of system? Do you have any ideas for improvement?

#1 for location developers in quality, price and choice, switch to HERE.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}