Join our Newsletter — 33% off our NHI Course
Home› Guides› Local File Inclusion vs Path Traversal: Read Access…
Guide Web & API Security

Local File Inclusion vs Path Traversal: Read Access vs Code Execution

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 14 November 2026 17 min read
On this page

Path traversal and local file inclusion are often reported as one bug, but one returns a file to the attacker and the other hands that file to an interpreter, and that difference decides whether you are dealing with a data leak or remote code execution. Both start from the same mistake: a file path built from input the application did not constrain. They diverge at the sink. This guide compares the two weakness classes side by side, explains how a traversal read becomes code execution when the sink is an include statement, shows why configuration files and secrets are the usual prize, and sets out the canonicalisation, safelist and runtime controls that close each one. It is for application security engineers, PHP platform owners and the reviewers who triage these findings, and is defensive throughout. For the traversal class on its own, see the Path Traversal Guide.

Key takeaways

  • The sink decides the severity. Traversal into a read or download function discloses files; the same input reaching include or require in PHP executes whatever PHP code the file contains.
  • LFI usually contains a traversal. MITRE describes local file inclusion as the case where remote download is unavailable or the attacker does not control the start of the filename, so a relative path traversal is needed to reach the target file.
  • Read access is already a credential incident. Environment files, framework configuration, cloud credential files and private keys are plain files, so a traversal read often yields non-human identity secrets that work from anywhere.
  • Safelists beat filters for both. Map an identifier to a fixed file, or resolve the canonical path and check containment by components; character blocklists alone fail against encoding and platform variants.
  • Runtime settings reduce, they do not fix. allow_url_include off, open_basedir and confinement profiles shrink the blast radius, but the PHP manual itself says open_basedir cannot be relied on when security is needed.

The short answer

Path traversal (CWE-22, Improper Limitation of a Pathname to a Restricted Directory) is a location problem: the final path escapes the directory the developer intended. What happens next depends on the function that receives the path. If it reads and returns the file, the attacker gets disclosure. If it writes, the attacker may overwrite code or drop a web shell.

Local file inclusion is an execution problem. MITRE files the PHP form as CWE-98, Improper Control of Filename for Include/Require Statement in PHP Program, a variant that is a child of CWE-829 Inclusion of Functionality from Untrusted Control Sphere and can precede CWE-94 code injection. The include family loads a file into the running program. CWE-98 lists its consequence as execution of unauthorised code or commands, either through a local file with executable PHP content or through PHP code placed into a data file that is later included.

So a traversal is a way of choosing a file; an inclusion is a way of running one. LFI often uses traversal to choose the file, which is why reports blur them. Remote file inclusion (RFI, CAPEC-193) includes a file from a URL and depends on a setting modern PHP disables by default.

Side-by-side comparison

DimensionPath traversalLocal file inclusion
Primary CWECWE-22, children CWE-23 (relative) and CWE-36 (absolute)CWE-98 (PHP), parent CWE-829; can precede CWE-94
CAPEC patternCAPEC-126 Path TraversalCAPEC-252 PHP Local File Inclusion
Typical sinkFile read, download, preview, export, archive extraction, file writeinclude, include_once, require, require_once, template or module loaders
What the attacker gets by defaultFile contents, or a write primitiveExecution of any PHP code inside the chosen file; non-PHP content is echoed into the response
Language spreadEvery language and platform with a filesystem APIMostly PHP; OWASP notes the same risk in other technologies such as JSP and ASP
Typical worst caseCredential theft from config files, then lateral movement with the stolen secretRemote code execution as the web worker identity
Strongest fixIndirect reference (generated ID mapped to a stored path)Fixed ID-to-file map; no user input in include paths at all
Main runtime backstopOS confinement, read-only mounts, rooted file APIsallow_url_include off, open_basedir, upload directories that never execute, confinement
ATT&CK view after exploitationT1083, T1005, T1552.001T1190, T1505.003, plus the traversal techniques when used for reading

Path traversal: threat model, architecture and failure modes

Threat model

The attacker wants a file the application can read but was never meant to serve. The realistic targets are files that grant further access: application configuration, environment files holding database passwords and API keys, cloud and container registry credential files, SSH and TLS private keys, and source code that reveals more endpoints. In ATT&CK terms this is T1083 File and Directory Discovery, T1005 Data from Local System and T1552.001 Credentials In Files. When the vulnerable product faces the internet, initial access is T1190 Exploit Public-Facing Application. A CISA and FBI Secure by Design alert on the class counted 55 directory traversal vulnerabilities in the Known Exploited Vulnerabilities catalogue.

Architecture in words

A handler receives a name, joins it to a base directory and passes the result to a file API. The validation step and the file API often see different representations of the same string: one before URL decoding, one after; one with forward slashes, one on a platform that also accepts backslashes; one before symbolic links resolve, one after. CAPEC-64 records the combination of slashes and URL encoding used to slip past validation logic.

Failure modes

The recurring causes are checking before decoding, string prefix containment checks, symbolic links resolved after the check, and archive entry names treated as trusted; OWASP ASVS 5.0 V5.3.3 requires decompression to ignore user-provided path information. The Path Traversal Guide covers each in depth.

Local file inclusion: threat model, architecture and failure modes

Threat model

The attacker wants the interpreter to run code of their choosing. CAPEC-252 describes three goals: loading old PHP files with known vulnerabilities, loading PHP files the attacker placed on the machine during a prior step, and otherwise changing application behaviour in unexpected ways. The chain therefore has two links. First, a way to influence the include path. Second, a file on the server whose contents the attacker can shape, or an existing file whose execution in this context is harmful. Any write path into the filesystem, such as an upload feature, a log the application writes, a session store or a cache, becomes part of the LFI attack surface even when it is safe in isolation.

Architecture in words

The PHP manual explains why inclusion is so much more dangerous than reading. An included file inherits the variable scope of the line that includes it, its functions and classes become global, and parsing starts in HTML mode and switches to PHP wherever a valid PHP open tag appears. A file that is mostly text but contains a PHP block will have that block executed. A bare name is searched through include_path, the calling script's directory and the working directory; absolute or dot-relative paths skip include_path. Prepending a directory and appending an extension narrows, but does not remove, the choice of file.

PHP also accepts stream wrappers in file functions. The manual lists wrappers such as file://, http://, php://, data:// and phar://, and a check that only looks for directory separators says nothing about a scheme prefix. Since PHP 8.0, metadata in a phar archive is no longer automatically unserialised, which the migration notes describe as a fix for vulnerabilities caused by object instantiation and autoloading. For the deserialisation side, see the Insecure Deserialisation Guide.

Remote inclusion

RFI needs allow_url_include, which defaults to 0, requires allow_url_fopen and has been deprecated since PHP 7.4.0. CWE-98 rates turning it off as moderate effectiveness because it stops remote inclusion only; the runtime table below sets out the related switches.

Failure modes

  • Dynamic module or language selection: a page, theme, lang or template parameter concatenated into an include path, the pattern CWE-98 uses as its example.
  • Extension suffix as the only control: forcing a .php suffix limits the target set but still allows any PHP file on disk, including old or vulnerable ones, which is CAPEC-252's first goal.
  • Executable upload directories: uploaded files stored under the web root or in a directory the include path can reach.
  • Error disclosure: include failures emit E_WARNING with the attempted path; the PHP 8.0 migration notes ask for display_errors off with error logging in production.
  • Legacy runtimes: old applications that relied on register_globals or remote includes, which CWE-98 advises removing.

Impact on secrets and configuration files

The two classes share the same first prize. A traversal read of an environment file or framework configuration returns database credentials, SMTP passwords, payment API keys and cloud access keys. An LFI that cannot reach a writable file still discloses non-PHP files, because their content is echoed into the response, so LFI is never less severe than traversal against the same path. If the include reaches attacker-shaped content, every secret the PHP worker can read, including environment variables, is exposed.

Asset on diskExposure through traversal readExposure through LFI executionControl that removes the prize
Environment and config files with database or API credentialsFull disclosureFull disclosure plus use from inside the trust boundarySecrets manager or workload identity; short-lived credentials
Cloud credential files and instance tokens cached on diskDisclosure, reusable from any networkDisclosure and live calls to metadata servicesWorkload identity federation; no static keys on hosts
Private keys for TLS, SSH and signingDisclosureDisclosure and signing as the serviceHSM, KMS or key vault with non-exportable keys
Session files and cachesSession theftPossible code execution if contents are attacker-influencedServer-side session store outside the filesystem; no user data in executable paths

Where identity fits: the most damaging outcome of either bug is usually a non-human identity credential that keeps working after the vulnerability is patched. Treat every confirmed traversal read or LFI as a credential exposure and rotate what the worker could read. See the Secrets Management Guide and Secrets in Backups and Snapshots.

Canonicalisation and safelist defences

The same design ladder works for both classes, with one difference: for include statements, the bottom rung (user-chosen names with a containment check) should not exist at all.

  1. No user input in the path. OWASP's file inclusion testing guidance names this the most effective fix: do not pass user-submitted input to any filesystem or framework API. ASVS 5.0 V5.3.2 requires file paths built from internally generated or trusted data, explicitly to protect against path traversal, LFI, RFI and SSRF.
  2. Identifier to file map. Users select an index or key; the application looks up a fixed filename and rejects anything else. CWE-98 calls this enforcement by conversion and OWASP recommends the same allow list approach.
  3. Accept-known-good validation. Where names must come from users, CWE-98 advises a strict character set, a single dot where feasible, no directory separators and an allowlist of extensions, and warns that denylists alone are insufficient.
  4. Decode once, canonicalise, check by components. For read and download paths only: decode exactly once, resolve to an absolute real path with symbolic links resolved, and confirm the result is the base directory or a descendant by comparing path components, not string prefixes. The Path Traversal Guide covers rooted APIs such as Go os.Root and Python tarfile filters.
  5. Consistent parsing. ASVS 5.0 V1.5.3 (Level 3) requires parsers for the same data type to behave consistently, naming different URI or file parsing behaviour exploited in RFI or SSRF.

PHP runtime backstops

Setting or practiceWhat it doesLimits
allow_url_include = 0Blocks URL wrappers in include and require (default 0, deprecated since 7.4.0)Remote inclusion only; LFI unaffected
allow_url_fopen = 0Disables URL-aware fopen wrappers (default 1)Breaks code that fetches URLs with file functions; does not stop traversal
open_basedirRestricts file access, including include, to listed directory trees; symlinks are resolved before the checkChangeable at runtime (INI_ALL); does not restrict Unix domain sockets; disables the realpath cache; the manual calls it an extra safety net that cannot be relied on
disable_functionsRemoves listed internal functions such as process execution functionsSystem level only; the manual says it can be circumvented
display_errors off, log_errors onStops include warnings leaking pathsErrors still need monitoring in logs

Run each PHP-FPM pool as its own user, keep upload and cache directories non-executable and add AppArmor or SELinux confinement. CWE-98 rates sandboxing as limited effectiveness on its own because it confines the operating system impact rather than the application. For a full baseline see PHP Configuration Hardening and the PHP and WordPress Security Guide.

Worked scenario

A legacy PHP customer portal has two findings in the same release. The first is a document download endpoint that takes a filename parameter and serves files from a reports directory. The second is a page loader that takes a section name, prefixes a views directory and appends .php before calling include.

Triage: the download endpoint is CWE-22. Testers can read the application's environment file. That file holds a database password and a payment provider API key. The page loader is CWE-98: it can load PHP files outside the views directory, including an old administrative script left in the deployment that skips authentication. That alone is a privilege escalation; combined with the avatar upload feature, which stores files under the web root, it is a credible path to code execution.

Response: the team rotates the database password and payment key immediately and reviews the provider's audit log for unfamiliar source addresses, because the read finding means the secrets must be treated as exposed. The download endpoint moves to generated identifiers mapped to stored paths. The page loader is replaced with a fixed array mapping section keys to view files, with any other key returning a 404. The stale administrative script is deleted from the build, uploads move to object storage served through a handler, and open_basedir plus a per-pool system user are added as defence in depth. Retesting covers both endpoints and the upload path together.

Decision checklist for triage and design

  • Which function receives the path? Read or download: rate as traversal by what is readable. Include, require or a template loader: rate as code execution unless proven otherwise.
  • Can the attacker influence any file the include can reach? Uploads, logs, sessions and caches all count. If yes, treat as remote code execution.
  • What credentials can the worker read? If any secret is on disk or in the environment, rotation is part of remediation, not an optional extra.
  • Is the vulnerable code yours or third party? For third-party code you cannot change, CWE-98 lists an application firewall as a moderate interim control. See the Web Application Firewall Guide.
  • Small team or large estate? Small teams should rely on framework routing and view resolution; large estates should ban dynamic include paths by static analysis rule.

How to implement

  1. Inventory sinks: search every repository for include, include_once, require, require_once, template and view loaders, and every read, download and extraction call. Mark which ones take any external value, including values from configuration files that users supply.
  2. Remove dynamic includes first: CWE-98 rates manual white-box review as highly effective because applications contain few include statements. Replace each dynamic one with a fixed map.
  3. Fix read paths by exposure: unauthenticated downloads and archive handling first, then authenticated features, then internal tools.
  4. Take secrets off reachable disk: move credentials to a secrets manager or workload identity so any residual flaw finds nothing reusable.
  5. Apply runtime backstops in staging: set allow_url_include and, where the application allows, allow_url_fopen to 0, add open_basedir per pool and run AppArmor or SELinux in complain or permissive mode for two to four weeks before enforcing; rollback is a profile switch.
  6. Gate new code: add a static analysis rule that fails builds when request data flows into include or file APIs outside the approved helper, and keep both classes in every penetration test scope. See the Web Application Security Testing Guide.

Detection and measurement

SignalSourceWhat it suggests
Parameters containing parent directory sequences, absolute paths, encoded separators or stream wrapper schemesWeb server, reverse proxy and WAF logsProbing for either class; alert on successful responses, not attempts
Include warnings naming unexpected pathsPHP error logActive LFI testing or a broken loader
PHP worker opening files outside its code and data directoriesauditd, EDR file events (D3FEND D3-FAPA File Access Pattern Analysis)Successful traversal or inclusion
New PHP content in upload, cache or log directoriesFile integrity monitoringPreparation for an inclusion chain or a web shell (T1505.003)
Application credentials used from new addressesCloud and SaaS audit logsA read already succeeded

Metrics that show progress:

  • Dynamic include or require statements taking external input, trending to zero.
  • File API calls with external input that bypass the approved helper.
  • Percentage of PHP pools with allow_url_include off, open_basedir set and a dedicated system user.
  • Long-lived secrets found on web hosts per scan.
  • Mean time to patch KEV-listed CWE-22 and CWE-98 flaws on internet-facing systems; the CISA KEV catalogue (version 2026.10.21) tags two entries with CWE-98, in Synacor Zimbra Collaboration Suite (CVE-2025-68645) and WordPress Core (CVE-2026-87902).

Common failure patterns

  • Rating LFI as information disclosure: the report shows a system file being read, so the finding is filed as medium. The include sink means code execution is one writable file away.
  • Blocklisting dot-dot: filters miss encoded, double-encoded and platform variants and do nothing about absolute paths or wrapper schemes.
  • Relying on open_basedir: it is runtime-changeable and the PHP manual says it cannot be relied upon; it is a backstop, not the control.
  • Executable uploads: user files stored under the web root give an LFI or misconfigured server the second link of the chain. See the File Upload Security Guide.
  • Stale scripts in deployments: backup copies, installers and old admin tools left on disk are exactly what CAPEC-252 describes loading.

Framework mapping

FrameworkReferenceRelevance
MITRE CWECWE-22, CWE-23, CWE-36; CWE-98, CWE-829, CWE-94Weakness classification for findings and CVE records
MITRE CAPECCAPEC-126, CAPEC-64; CAPEC-252, CAPEC-193Attack patterns for test planning
OWASP ASVS 5.0V5.3.2, V5.3.3, V1.3.2, V1.5.3Verification requirements
NIST SP 800-53 Rev. 5SI-10 Information Input Validation; SA-11 Developer Testing and Evaluation; CM-7 Least Functionality; AC-6 Least Privilege; SI-4 System MonitoringValidation, testing, runtime hardening, confinement, monitoring
NIST CSF 2.0PR.PS-06; DE.CM-09; ID.RA-01Secure development, runtime monitoring, vulnerability identification
ISO/IEC 27001:2022Annex A 8.28 Secure codingPolicy anchor
MITRE ATT&CKT1190, T1083, T1005, T1552.001, T1505.003Detection engineering
MITRE D3FENDD3-LFAM Local File Access Mediation; D3-FAPA File Access Pattern AnalysisCountermeasures

Practitioner checklist

  • Classify each finding by sink: read, write or include.
  • Replace every dynamic include or require with a fixed identifier to file map.
  • Use generated identifiers for downloads; where names are unavoidable, decode once, canonicalise and check containment by path components.
  • Set allow_url_include to 0 everywhere and allow_url_fopen to 0 where the application allows.
  • Configure open_basedir and a dedicated system user per PHP pool, as defence in depth only.
  • Store uploads outside the web root, serve them through a handler and never let them execute.
  • Remove stale scripts, installers and backups from deployed artefacts.
  • Rotate every credential the worker could read after any confirmed traversal or LFI.
  • Add static analysis rules and penetration test scope for both classes.

Standards and references

Related NHI Mgmt Group resources: Path Traversal Guide, PHP and WordPress Security Guide, PHP web shells, Secrets Management Guide.

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 14 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.