Skip to content

htaccess to deny access, except for includes

It’s usually a bad idea to allow php include files to be directly accessed. My general method is to either declare a constant in the index.php and check for that constant in the included file or make sure that the included file doesn’t match $_SERVER[‘REQUEST_URI’].

Sure, either of those work. But I came across a much easier way using .htaccess and am now kicking myself for not using it earlier.

Just put the following in an .htaccess file in the folder with your include files.

# Block direct requests for files in this folder
deny from all

The first line is just a comment, so you could even take that off.

Trying to directly access one of the PHP files will result in a forbidden error, but the files can still be included through another script.

Published inProgramming

2 Comments

  1. Very good security measure. But it would be better if there is a single htaccess file in the root directory which protects the folder using

  2. For the project I’m working on, that’s actually what I did. All the includes are in one main folder with subfolders. The main folder got the .htaccess.

Leave a Reply

Your email address will not be published. Required fields are marked *