Skip to content

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.

3. Validate the input strictly

4. Harden the runtime and wrappers

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

Per-technique remediation

Each technique page carries a remediation section and a vulnerable → fixed code sample specific to that attack: