June 18, 2013

Disable direct access to files in PHP

Mr Me’s Question:

I’ve already checked the issue disable access to included files , but I am wondering if that’s the best solution.

Context: I’m building a bootstrap class for my PHP Framework, and realized that there are multiple solutions to this security issue.

After researching and reading posts like the one I mentioned at first and others related to htaccess, I think that there are basically three types of solutions:

1 – Checking a constant (like in the post I linked)

if(!defined('THIS_IS_NOT_A_DIRECT_ACCESS')) {
    header('HTTP/1.1 404 Not Found');
    include('./../error/404.php');
    die;
}

Or

require('../error/include_file.php');
//
if(!defined('THIS_IS_NOT_A_DIRECT_ACCESS'))
{
    header('HTTP/1.1 404 Not Found');
    include('404.php');  
    die; 
}

2 – Redirecting all calls to the Bootstrap and making a clever filtering.

//Something like
// if $urlRequested it's a file
    // Go to Error
// else if $urlRequested it's not a controller
    // Go to Error
// else 
    // Execute Controller Logic.

3 – Setting htaccess.

# Redirecting calls for non-directories, files or links
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA]

# Redirecting the rest of the calls to the error page.
RewriteRule ^(.+)$ index.php?url=error/404 [QSA]

Personally I think the solution 3 is the most interesting, but I am pretty new in the Htaccess control so I wonder if this is a safe solution.

For the purists and minimalists, the Question in here would be:
Are these (the three examples) nice direct access control systems for Apache-PHP applications? Else, which would be the safest approach? And the simplest?

This is a debatable topic but .htaccess rules applies to all the document on that particular directory. While applying 1 or 2 you may have to include that portion on every file.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!