Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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'];
mysql_query($query);

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
</FILES>

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?

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}