PHP Security - Block Access to Include Files Using .htaccess
Join the DZone community and get the full member experience.Join For Free
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$">
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?
Opinions expressed by DZone contributors are their own.
Integrating AWS With Salesforce Using Terraform
Scaling Site Reliability Engineering (SRE) Teams the Right Way
Automating the Migration From JS to TS for the ZK Framework
Never Use Credentials in a CI/CD Pipeline Again