5.1. Exposed Source Code
A major concern regarding includes is the exposure of source code. This concern is largely a result of the following common situation:
This state results in your includes being accessible via URL. Worse, they are not parsed by PHP and instead are treated as plain text, resulting in your source code being displayed in the user's browser (see Figure 5-1).
Figure 5-1. Raw source code displayed in a browser
This problem is very easy to avoid. Simply organize your application so that all includes are stored outside of document root. In fact, a best practice is to consider all files stored within document root to be public.
While this may sound unnecessarily paranoid, many situations can cause your source code to be revealed. I have witnessed Apache configuration files being overwritten by mistake (and going unnoticed until the next restart), inexperienced system administrators upgrading Apache but forgetting to add PHP support, and a handful of other scenarios that can expose source code.
By storing as much of your PHP code outside of document root as possible, you limit this risk of exposure. At the very least, all includes should be stored outside of document root as a best practice.
Several practices can limit the likelihood of source code exposure but not address the root cause of the problem. These include instructing Apache to process .inc files as PHP, using a .php file extension for includes, and instructing Apache to deny requests for .inc resources:
<Files ~ "\.inc$"> Order allow,deny Deny from all </Files>
While these approaches have merit, none of them is as strong as placing includes outside of document root. Do not rely on these approaches for protection. At most, they can be used for Defense in Depth.