3.1. Exposed Access Credentials
One of the primary concerns related to the use of a database is the disclosure of the database access credentialsthe username and password. For convenience, these might be stored in a file named db.inc:
<?php $db_user = 'myuser'; $db_pass = 'mypass'; $db_host = '127.0.0.1'; $db = mysql_connect($db_host, $db_user, $db_pass); ?>
Both myuser and mypass are sensitive, so they warrant particular attention. Their presence in your source code poses a risk, but it is an unavoidable one. Without them, your database cannot be protected with a username and password.
If you look at a default httpd.conf (Apache's configuration file), you can see that the default type is text/plain. This poses a particular risk when a file such as db.inc is stored within document root. Every resource within document root has a corresponding URL, and because Apache does not typically have a particular content type associated with .inc files, a request for such a resource will return the source in plain text (the default type), including the database access credentials.
To further explain this risk, consider a server with a document root of /www. If db.inc is stored in /www/inc, it has its own URLhttp://example.org/inc/db.inc (assuming that example.org is the host). Visiting this URL displays the source of db.inc in plain text. Thus, your access credentials risk exposure if db.inc is stored in any subdirectory of /www, document root.
The best solution to this particular problem is to store your includes outside of document root. You do not need to have them in any particular place in the filesystem to be able to include or require themall you need to do is ensure that the web server has read privileges. Therefore, it is an unnecessary risk to place them within document root, and any method that attempts to minimize this risk without relocating all includes outside of document root is subpar. In fact, you should place only resources that absolutely must be accessible via URL within document root. It is, after all, a public directory.
If outside factors prevent you from achieving the optimal solution of placing all includes outside of document root, you can configure Apache to reject requests for .inc resources:
<Files ~ "\.inc$"> Order allow,deny Deny from all </Files>