
Credits: pexels.com (Photo by Goumbik)
There’s a certain unease that creeps in when you spot an unchecked include statement in a PHP project. RFI (Remote File Inclusion) and LFI (Local File Inclusion) are traps we see students fall into all the time, they open the door for attackers to run their own code or peek at sensitive files.
We’ve learned that dodging these issues takes more than just good intentions. It’s about strict coding habits, tight server settings, and never letting user input run wild. Here’s the way we teach it at the bootcamp, and what’s kept our own demo apps from getting wrecked.
Key Takeaways
- Never trust user input in include statements, always validate and whitelist.
- Shut down remote file inclusion in PHP’s config, it blocks a whole class of attacks.
- Stick to absolute paths, sanitize everything, and keep file permissions tight.
Understanding Remote and Local File Inclusion Vulnerabilities
Definitions and Differences Between RFI and LFI
RFI happens when a PHP script lets someone pull in a file from an outside URL, usually because it’s taking user input and running with it. Suddenly, an attacker’s code is running on your server.
LFI is a little different, here, the attacker gets the script to include files already on the server. Sometimes it’s just reading config files, but with the right setup, it can turn into code execution too. Both are nasty.
Security Risks and Potential Impacts
RFI is a straight shot to remote code execution. If someone can point your script to their own code, they can take over the server. LFI can leak passwords, configuration files, or worse, sometimes it leads to full compromise if the stars align (and by stars, I mean bad security). We’ve seen both lead to data breaches and outages that could’ve been avoided.
Identifying and Detecting File Inclusion Weaknesses
Reviewing Code for Unsafe include/require Usage
We make it a habit to scan for include, require, and their cousins (include_once, require_once) using anything from user input. This is the first thing we look for in code reviews.
Example of risky code:
<?php
$module = $_GET[‘module’];
include $module; // Dangerous if $module is not validated
?>
Utilizing Automated Security Scanners
Automated tools help us catch what we might miss. They’re good at flagging sketchy includes or suspicious patterns, and we run them before anything goes live.
Performing Penetration Testing for Inclusion Exploits
We’ll try feeding in remote URLs or directory traversal tricks during testing. If the app spits out errors or includes weird files, we know there’s a problem.
Configuration and Coding Best Practices to Prevent RFI/LFI

Credits: pexels.com (Photo by Digital Buggu)
Disabling Remote File Inclusion in PHP Configuration
Turning off remote file inclusion is one of those things that’s easy to forget, but it’s saved us more than once:
allow_url_include = Off
allow_url_fopen = Off
With those off, PHP won’t fetch files from URLs, RFI attacks get blocked at the door. (1)
Avoiding Direct Inclusion of User Input
We never let raw user input touch an include or require. It’s just asking for trouble. Instead, we use a whitelist.
Employing Whitelists for Allowed Included Files
If you need dynamic includes, limit it to files you know are safe:
$whitelist = [‘home.php’, ‘about.php’, ‘contact.php’];
$page = $_GET[‘page’];
if (in_array($page, $whitelist)) {
include __DIR__ . ‘/pages/’ . $page;
} else {
include __DIR__ . ‘/pages/404.php’;
}
This simple check has stopped more than one attempted attack in our student projects.
Using Absolute or Fixed Paths for File Inclusion
Relative paths are too easy to mess with. We define a base directory and stick to absolute paths:
define(‘BASE_PATH’, __DIR__ . ‘/pages/’);
include BASE_PATH . ‘home.php’;
Validating and Sanitizing User Input
Sanitizing input helps, but it’s not a silver bullet. We’ll use basename() to strip out directory traversal, but we always combine it with a whitelist.
$page = basename($_GET[‘page’]); // Removes directory traversal parts
Strengthening Server and Application Defenses
Restricting File and Directory Permissions
We keep file permissions strict, only what’s needed, nothing more. Sensitive files get locked down, and execution is disabled where it’s not needed.
Deploying Web Application Firewalls (WAF)
A good WAF can spot RFI/LFI attempts, things like http:// in a parameter or ../ in a path. We’ve seen them block attacks that slipped through code checks. (2)
Maintaining Updated PHP Versions and Dependencies
Outdated PHP or libraries are just asking for trouble. We keep everything patched to close off old exploits.
Implementing Secure Error Handling and Logging
We never show full error messages to users. Instead, errors get logged for us to review. Attackers don’t need a map of our file system.
Practical Tips from Our Experience
There was a site we reviewed where user input went straight into an include, no checks. Someone used it to run a remote script, and the site lost data. After switching to a whitelist and turning off remote includes, the problem disappeared.
Another time, directory traversal let an attacker read config files. Using basename() and absolute paths shut that down fast.
Summary Table of Prevention Techniques
Credits: Loi Liang Yang
Prevention Method | Description |
Disable allow_url_include | Stops remote file inclusion globally |
Use Whitelist | Only include files you know are safe |
Use Absolute Paths | Avoid relative/user-controlled paths |
Sanitize Input | Strip out ../ and URL schemes |
Restrict File Permissions | Lock down sensitive files and directories |
Use Web Application Firewall | Catch/block malicious inclusion attempts |
Keep Software Updated | Patch PHP and dependencies regularly |
Avoid Direct User Input in Include | Never trust raw input in includes |
Conclusion
We’ve seen it again and again, RFI and LFI attacks are almost always preventable. Don’t trust user input, lock down your settings, and validate everything. Stack up these defenses, and you’ll keep your PHP apps safe from some of the nastiest tricks out there.
Want to level up your secure coding skills? Join the Secure Coding Practices Bootcamp, a hands-on, expert-led training designed to help developers build safer software from day one.
FAQ
How can I avoid PHP remote file inclusion RFI LFI issues?
To avoid PHP remote file inclusion RFI LFI problems, disable allow_url_include and avoid dynamic file inclusion. Stick to static file inclusion and whitelist file inclusion targets. Use php file_exists check and php realpath validation to confirm paths.
Avoid eval function PHP and use PHP security best practices like input validation, secure session storage, and php security headers. Applying OWASP Top 10 prevention helps reduce risk from RFI and LFI.
What PHP input validation techniques help stop file inclusion attacks?
Use PHP input validation techniques like php filter_var function, php regex validation, and symfony input validation. Always sanitize user input PHP and use server-side input filtering. For file paths, validate with php realpath validation and basename function usage.
Restrict file extensions and use MIME type verification. Never trust URL input, use url parameter sanitization and apply secure file inclusion patterns along with blacklist dangerous characters.
How should I configure php.ini for secure file handling?
Use a php.ini secure configuration checklist to disable allow_url_include and disable allow_url_fopen. Turn off phpinfo exposure and disable dangerous PHP functions. Set php open_basedir restriction and reduce php realpath cache size.
Limit session risk with php session security settings and secure session cookie flags. Also apply the php.ini hardening checklist and follow PHP secure coding guidelines for maximum protection.
What are the safest ways to handle file uploads in PHP?
Secure file upload handling requires validate upload file size, check file signatures, and verify MIME types. Store files in a secure file storage location outside the web root. Use secure file permissions and disable directory listing.
Always encrypt sensitive files if needed. Laravel secure file handling and php temp file security practices can help too. Monitor file inclusion attempts and apply PHP anti-malware scanning regularly.
How can I reduce the risk of local file inclusion in PHP?
To block local file inclusion protection issues, use whitelist file inclusion and php include path restriction. Validate all input using php filter_var function, sanitize user input PHP, and use php realpath validation.
Avoid dynamic file inclusion and stick to using absolute file paths. Implement php chroot jail implementation where needed and enforce secure development lifecycle practices like static code analysis and regular code audits.
What role do session and cookie settings play in file inclusion security?
PHP session security settings matter, use httponly session cookies, php session_regenerate_id, and secure session cookie flags. This stops attackers from hijacking sessions that could exploit file inclusion vulnerabilities.
Store sessions using secure session storage and apply PHP security headers like strict-transport-security header. Don’t forget x-content-type-options header and content security policy to reduce injection risk through improperly included files.
How do I monitor or log file inclusion threats?
Enable php file inclusion logging and monitor file inclusion attempts with proper audit tools. Use mod_security rules, web application firewall setup, and php security linter tools to catch bad patterns.
Log errors securely and disable error reporting production to avoid giving away paths. Monitor uploads and use static code analysis and PHP vulnerability scanning to find and patch PHP vulnerabilities.
What are the best ways to harden my PHP environment?
Start by updating PHP version and applying PHP environment hardening tactics like disable phpinfo exposure, use php suhosin extension, and enforce secure deployment practices. Encrypt sensitive files and use secure backup strategies.
Prevent php remote code execution prevention and cwe-98 mitigation with strict input validation and secure error messages. Train your team with PHP security training to build awareness and resilience.
Related Articles
- https://securecodingpractices.com/secure-file-io-operations-net-framework-core/
- https://securecodingpractices.com/spring-security-best-practices-configuration/
- https://securecodingpractices.com/async-await-error-handling-security-node-js/
References
- https://en.wikipedia.org/wiki/File_inclusion_vulnerability
- https://www.imperva.com/docs/HII_Web_Application_Attack_Report_Ed5.pdf