Preventing LFI/RFI is one of the simpler defender problems — just don’t pass user input to file inclusion functions. The nuances are around apps that must vary files based on user input (templating, localization), where the defense is strict allowlisting.

Primary Defense — Don’t Use User Input in Paths

Where possible, remove the user’s influence entirely:

// bad
include($_GET['page'] . '.php');
 
// better — allowlist of page IDs
$pages = ['home' => 'home.php', 'about' => 'about.php'];
include($pages[$_GET['page']] ?? 'home.php');

The user picks an identifier, the code maps it to a path. No user string touches the filesystem.

Strict Allowlist (If User Input Must Be in Path)

When identifier mapping doesn’t fit (e.g. dynamic localization), validate that input matches a known-good set:

$allowed = ['en', 'de', 'fr', 'es'];
if (!in_array($_GET['lang'], $allowed, true)) {
    die('invalid');
}
include("./languages/" . $_GET['lang'] . ".php");

Strict equality (===) matters. A looser check like in_array without the third argument allows type coercion bypasses.

Blacklist Is Not Enough

Common mistakes:

// doesn't block ....//
if (strstr($_GET['file'], '../')) die();
 
// doesn't block %2e%2e%2f (URL-encoded)
if (strpos($_GET['file'], '..') !== false) die();
 
// doesn't block php://filter
if (preg_match('/\.php$/', $_GET['file'])) die();

All of these fail on one or more of the bypasses in the Filter Bypass section. Don’t try to blacklist your way out of LFI.

Canonicalization

Resolve the final path before passing it to inclusion. If the resolved path is outside the allowed directory, reject:

$base = realpath('./safe-dir/');
$target = realpath($base . '/' . $_GET['file']);
 
if ($target === false || strpos($target, $base) !== 0) {
    die('path escape');
}
 
include($target);

realpath() resolves ../, symlinks, and redundant separators. The check confirms the final path still starts with your base directory.

Caveat: realpath returns false for non-existent files, which can create logic bugs. Make sure the fallback path is safe.

Configuration Hardening

Server-level settings that neutralize whole classes of LFI escalation:

PHP

; disable remote inclusion entirely
allow_url_include = Off
 
; disable remote fetches entirely (also stops SSRF via file_get_contents)
allow_url_fopen = Off
 
; restrict filesystem access to specific directories
open_basedir = /var/www/html/:/tmp/
 
; disable dangerous functions (blocks LFI-to-RCE even if achieved)
disable_functions = exec,passthru,shell_exec,system,proc_open,popen

Web Server

Deny access to logs, configs, and sensitive directories at the web server level:

# Apache
<DirectoryMatch "^/var/log/">
    Require all denied
</DirectoryMatch>

Prevents direct URL access even if path traversal succeeds. Doesn’t block LFI reading the file (which happens via include, not HTTP), but blocks lateral exploitation.

Platform-Level Isolation

  • Run the web server as a low-privilege user — limits readable files
  • Use containers with read-only filesystems for the web code
  • Mount log directories with noexec (prevents log-poisoning RCE via execve)
  • SELinux / AppArmor policies that restrict the web process’s filesystem access
  • Segregate the DB container from the web container (SQL dumps can’t reach /etc/passwd)

Logging and Detection

  • Alert on requests containing traversal patterns (../, %2e%2e, ....//)
  • Alert on php://filter, data://, expect:// in URLs
  • Monitor for unusual include() paths in PHP error logs
  • Watch for spikes in requests to paths that shouldn’t exist (.php file fuzzing)

Checklist Summary

  1. Don’t pass user input to inclusion functions — use identifier-to-path mapping
  2. If unavoidable, strict allowlist with in_array($x, $allowed, true)
  3. Canonicalize paths with realpath and verify prefix containment
  4. allow_url_include = Off, allow_url_fopen = Off in php.ini
  5. open_basedir restricting filesystem access
  6. disable_functions neutering execution primitives
  7. Web server denies direct access to log and config directories
  8. Monitor and alert on traversal / wrapper patterns in logs

Any one of these breaks the common attack chain. All of them together cover almost every real-world LFI scenario.