PHP Security Tip #9
Sometimes it’s the simplest ideas that are the most powerful. This one sounds simple but I’m always surprised at how few people understand and actually implement this idea.
Keep sensitive data and code out of your web tree
Consider this directory structure.
/htdocs
/includes
/images
/js
If you store your database credentials in a file named db.inc and place it in the /includes directory, it is possible for someone to download your the information in that file by going to http://example.com/includes/db.inc. Since most web servers aren’t given explicit instructions on how to deal with .inc files, they are treated as text if requested directly. The ramifications of this are obvious. If you store your database credentials in a file with an extension other than .php and inside your web server’s document root, there’s a good chance that you are leaking information.
The solution is simple. Place all sensitive data outside of your web server’s document root. Many experts now advocate placing most, if not all, of your php code outside of your web server’s document root. Since PHP is not limited by the same restrictions are you web server, you can make a directory on the same level as your document root and place all of your sensitive data and code there.
/phpinc
/includes
/htdocs
/images
/js
=C=

Comments
1. End any PHP based files with .php (e.g. db.inc.php instead of db.inc)
2. Use an .htaccess file if you do not wish to re-name the files to prevent reading
3. Add the type as PHP to the .htaccess to prevent reading
The Apache config to put in your .htaccess file to restrict access to all files with a .inc extension is:
<FilesMatch ".inc$">
Order allow,deny
Deny from all
</Files>
if ( ! defined( 'IN_MYAPP' ) )
{
print "Direct execution of this script is not allowed";
exit();
}
Then define the constant 'IN_MYAPP' globally in any files that should be executed directly (such as index.php). This way, you can be sure that nobody is calling your file with predefined variable values to execute malicious code.
"3. Add the type as PHP to the .htaccess to prevent reading"
Clarify this for me.
Thanks.