Securely Including Files – include, require etc.
Posted by Jon Lee in Web Development, tags: includes, PHP, securityWhen creating large applications or web sites, it is often useful to abstract it to different classes or even to just compartmentalize your code. For example, create a single file containing all your database functions and simply include it with files that need to use it.

What is an Include File
Let’s say your entire site has a common header, you would put your header code in a file, say header.php and then include it from your other pages using:
<?php include(“header.php”); ?>
Likewise, you could use require instead of include, which will not load your page any further if the required file is not found. If you are including a file of PHP functions on the other hand, you would use the include_once or require_once command to make sure the same file doesn’t accidentally get included twice (which would cause PHP to barf up errors about duplicate function names).
Security Concerns
Security concerns arise when you do not wish users to be able to visit these include files directly. Here are several ways of securing them:
- Name your include directory something unique
Usually, all of these include files are stored in a single directory for organizational purposes. That’s actually a good thing but more often than not, the directory is called inc or include — not exactly hard to guess. - Give it only the necessary permissions and ownership
The include files only need to be able to be read by the server and no one else, by setting the appropriate permissions you’ll make it invisible to users’ web browser. - Put it outside of your web accessible directory
This is perhaps the safest method. By placing this somewhere outside your web accessible directory, your scripts can still access it but no one else will be able to. For example, if your web page is in the www directory, then simply place your include files in a directory alongside your www directory (not inside).
By combining the 3 above techniques, you can be guaranteed that no one will be able to access your include files directly!
Popularity: 2% [?]
Entries (RSS)