When developing PHP websites, an important consideration is the security and organization of your code. One best practice that significantly enhances security involves storing PHP files used with include
and require
statements outside the public web-accessible directory. This approach not only helps in maintaining cleaner code but also adds an extra layer of protection against potential security breaches.
Why Store Files Outside the Web Directory?
By placing PHP files that are included or required into a directory not accessible from the web, you mitigate several security risks. These files might contain sensitive data including passwords, api-keys, sensitive configuration settings, or essential functions that should not be exposed to unauthorized users. If these files are within the web directory, there’s a risk that someone could access them directly if they knew the file path.
Benefits of This Approach
- Increased Security: Keeping PHP files outside the web root ensures that they cannot be directly accessed or viewed through a browser. This is particularly important for files containing credentials, business logic, or any other sensitive information. While many PHP scripts will not be visible if directly accessed, should PHP stop working on the server, the PHP files being served as plain text!
- Better Organization: Separating your core PHP files from the public-facing web directory helps in keeping the directory structure organized. This makes it easier to manage your code and enhances maintainability.
- Reduced Risk of Exploits: If an attacker gains access to your web directory or is able to perform an index, they should not have access or visibility to your core PHP scripts if they are stored outside the web root. This limits the potential damage an attacker can cause.
Implementing This Best Practice
To implement this, you should structure your project so that only necessary files (like HTML, CSS, and public JavaScript) reside within the web directory. PHP files that handle backend logic, database interactions, or configuration should be stored in a separate directory outside of this public area. You can then use relative paths in your PHP include
and require
statements to include these files. For instance:
In this example, the nav.php
and footer.php
files are stored in an includes
directory one level up from the web root, making them inaccessible directly via a URL.
include '../includes/nav.php';
require '../includes/footer.php';
Conclusion
Storing PHP includes and requires outside the web directory is a simple yet effective strategy to enhance the security and organization of your website. By following this best practice, you protect sensitive information from unauthorized access and maintain a cleaner, more manageable codebase. Implementing this approach will help ensure that your PHP applications remain secure and efficient.