How to prevent LFI and path traversal
How to prevent Local File Inclusion and path traversal comes down to one principle: never let untrusted input decide which file the application opens. The controls below are ordered by how reliably they stop the bug — prefer the first, and treat the rest as defence in depth. Blocklists that try to strip ../ are deliberately left out: every technique in this reference exists because they fail.
1. Map keys to files with an allowlist
The strongest fix removes the file path from attacker control entirely. Accept a short key and look it up in a server-side map of known, fixed paths. Anything not in the map is rejected. Because the attacker never supplies a path, traversal, encoding, null bytes, wrappers and remote URLs all become impossible in one step.
$pages = ['home' => 'home.php', 'about' => 'about.php'];
$key = (string) ($_GET['page'] ?? 'home');
if (!isset($pages[$key])) { http_response_code(404); exit; }
include __DIR__ . '/pages/' . $pages[$key];2. Canonicalize, then verify the base directory
When a filename component is unavoidable, resolve the final path to its canonical form and confirm it still lives inside the intended directory before opening it. Resolve first and validate second — never validate a value that a later layer will decode or resolve again, or encoding bypasses slip through the gap.
- PHP:
realpath()thenstr_starts_with($path, $base). - Node.js:
path.resolve()thenfull.startsWith(base + path.sep). - Python:
os.path.realpath()thenpath.startswith(base + os.sep). - Java:
Path.normalize().toRealPath()thenstartsWith(baseReal).
3. Validate the input strictly
- Reject any value containing a path separator,
.., a NUL byte, or a URL scheme (php://,data://,file://,phar://) when a bare filename is expected. - Use
basename()(or the platform equivalent) to discard any directory component. - Enforce a strict pattern and a sane maximum length.
- Decode and normalise exactly once, in a single well-defined place.
4. Harden the runtime and wrappers
- PHP: set
allow_url_include=Offandallow_url_fopen=Offunless a reviewed feature needs them; this blocks remote inclusion anddata:///php://inputcode execution. - Disable dangerous stream wrappers for dynamic-include code paths; do not install the
expectextension on web hosts. - Confine file access with
open_basedir, a chroot, or a container so logs, sessions,/procand secrets are out of read scope. - Run as a low-privilege user, keep
disable_functionsset, and block outbound SMB on Windows to stop UNC inclusion and NetNTLM leakage.
5. Keep secrets out of readable files
Source disclosure through php://filter is only damaging if the source contains secrets. Store credentials in environment variables or a secret manager, outside the web root and outside readable config files, so a successful read yields nothing useful.
6. Detect attempts in logs
- Alert on
../and its encoded forms (%2e%2e,%252e,%c0%ae), on NUL bytes (%00), and on URL/UNC values in file parameters. - Flag
php://filter,data://,php://input,phar://and longconvert.iconvfilter chains. - Correlate log lines containing
<?phpwith later requests that include a.log,/procorsess_path — a strong log-poisoning / inclusion signal. - Canonicalize-then-validate server-side rather than relying on a WAF rule alone; rules catch tooling, the code fix catches the bug.
Per-technique remediation
Each technique page carries a remediation section and a vulnerable → fixed code sample specific to that attack:
- Basic path traversal — Walk out of the intended directory with ../ to read arbitrary files.
- Absolute path inclusion — Supply a full path like /etc/passwd directly — no ../ needed.
- Encoding bypass — Encode the dots and slashes so the ../ filter never sees them.
- Filter-strip bypass — Craft ....// so removing one ../ leaves another ../ behind.
- Null byte injection — Terminate the string with %00 to drop an appended .php extension.
- Path truncation — Pad with ./ and trailing dots so an appended extension is cut off.
- Extension bypass — Make an appended extension harmless with ?, #, ; or a wrapper.
- php://filter source read — Base64-encode PHP source so include returns code, not output.
- php:// & data:// RCE — Feed PHP to include via data://, php://input, or expect://.
- PHP filter chain RCE — Chain iconv filters so php://filter emits a PHP payload in memory.
- Log poisoning — Inject PHP into a log via User-Agent, then include the log.
- Session / upload inclusion — Plant PHP in a session file (/tmp/sess_<id>), then include it.
- /proc inclusion — Smuggle PHP via User-Agent into /proc/self/environ, then include it.
- zip:// & phar:// wrappers — Include PHP packed inside an uploaded zip or phar archive.
- Remote file inclusion — Make include fetch and run PHP from your own URL or SMB share.