Validate against an allowlist. Treat all external input as malicious and accept only values that strictly conform to the required syntax, type, length, range, and business rules. For filenames, use a stringent character allowlist, preferably permitting only a single . where feasible, exclude directory separators such as /, and restrict extensions to an approved set. Do not rely solely on denylists or character removal, since alternate separators and other representations may bypass them.
Canonicalize before validation. Decode and canonicalize input once into the application’s internal representation before applying validation. Use a built-in canonicalization routine, such as realpath in C, getCanonicalPath in Java, GetFullPath in ASP.NET, realpath or abs_path in Perl, and realpath in PHP, and ensure the resulting path remains within the intended directory.
Enforce checks on the server. Duplicate client-side security checks on the server because attackers can alter client values or remove client checks. Prefer vetted libraries or frameworks that provide safe path-handling constructs. When the set of valid files or URLs is known, map fixed identifiers to those objects and reject all other inputs.
Limit impact and exposure. Run with the least privileges required, preferably using isolated accounts. Use a sandbox or jail such as chroot, AppArmor, SELinux, or applicable managed-code file permissions, while recognizing that this may only reduce impact and must be configured carefully. Store libraries, include files, and utility files outside the web document root where possible, or restrict direct web access to them.
Add operational defenses. An application firewall can provide defense in depth or temporary protection when the code cannot immediately be fixed, but it may miss input vectors, be bypassed, or reject legitimate requests. Keep error messages minimal and avoid disclosing filesystem paths; record necessary detail in protected logs. In PHP, do not use register_globals and do not create an unsafe emulation of it.