Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.
If you name it .inc, then anyone can go into your directory and download it -- ie. domain.com/mysql.inc will download, therefore if you have any sensitive data in it, they'll find it. Most people rename it to mysql.inc.php, so that they still have the "inc" identifier, but it's parsed as PHP (so if you define a few variables, it'll be a blank file if they access it directly).
It is not a good idea to have your modules processed by the PHP engine. This
includes renaming your modules with a .php extension as well as using
AddType to have .inc files treated as PHP files. Executing code out of context
can be very dangerous, because it's unexpected and can lead to unknown
results. However, if your modules consist of only variable assignments (as an
example), this particular risk is mitigated.
How can it be harmful by "Executing code out of context
can be very dangerous"?
If the code does administrative things or really does any logic processing automatically it can potentially have dire consequences if run independent of your other code.
Typically I insert code into these files that disallows direct access to the file via browser. This normally involves __FILE__ and $_SERVER['PATH_TRANSLATED'] or some variant thereof.
mysql_query("delete from records where date > '$last_date' ");
if someone calls 'delete.inc' directly, this can result in data loss.
That's quite stupid, actually. Nobody writes includes this way. Includes should only contain function or class definitions, no top-level code.
The best way to protect includes is to place them in a non-web directory or deny through htaccess, but this is not portable. Therefore, always use .php.
Ambush Commander wrote:If possible, make sure your includes perform completely harmless actions when included in isolation: i.e. they define classes and functions.
Agree. For me the most common thing being included (99% of the time) is class definitions. As for having files such as .inc or something similar you could use htaccess to limit accessibility to specific files.