Path Traversal Pattern Regex for PHP
/(?:\.\./|\.\.\\|%2e%2e%2f|%2e%2e/|\.%2e/|%2e\./|%252e%252e|\.\.%c0%af|\.\.%c1%9c|\.\./|%00|\.php\x00|\.asp\x00)/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching path traversal pattern, ported and verified for PHP. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your PHP project — whether you're validating in a Laravel validator, a WordPress plugin, or a standalone PHP script.
Php Implementation
<?php
// Path Traversal Pattern
// ReDoS-safe | RegexVault — Security > Injection Patterns
define('PATH_TRAVERSAL_PATTERN_PATTERN', '/(?:\.\.\/|\.\.\\|%2e%2e%2f|%2e%2e\/|\.%2e\/|%2e\.\/|%252e%252e|\.\.%c0%af|\.\.%c1%9c|\.\.\/|%00|\.php\x00|\.asp\x00)/');
function validate_path_traversal_pattern(string $input): bool {
return (bool) preg_match(PATH_TRAVERSAL_PATTERN_PATTERN, $input);
}
// Example
var_dump(validate_path_traversal_pattern("../../etc/passwd")); // bool(true)Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
../../etc/passwd | /var/www/html/index.html |
%2e%2e%2f | uploads/profile.jpg |
../../../ | C:\Users\Public\Documents |
..%c0%af | — |
%00injection | — |
When to use this pattern
This pattern is drawn from the Security > Injection Patterns category and carries a ReDoS-safe certification. That matters for PHP developers because especially relevant in PHP where PCRE backtracking limits can trigger silent failures on malicious input. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Path traversal defense must happen AFTER URL decoding. A filter that blocks ../ before decoding will miss %2e%2e%2f. Use the real path function (os.path.realpath in Python, path.resolve in Node.js) and verify it starts with the intended base directory.
Technical Notes
Path traversal (directory traversal) allows attackers to read files outside the intended directory. Double encoding (%252e = %) is used to bypass naive decoders. Null byte (%00) terminates strings in some C-based systems. Real defense: use path canonicalization and compare against the allowed base directory.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern