Reputation: 4941
I am looking for best way to check a path for traversal. Currently the path is in two parts, the $user_root and $input_path like below:
$user_root = '/var/www/users_root';
$input_path = '../../../';
$full_path = $user_root + $input_path;
I am useless when it comes to RegEx. I would like to check for traversal (remove if possible) as well as check the correct chars are in the path & filename for unix and windows.
Thanks
Upvotes: 0
Views: 3216
Reputation: 1759
Why not just check for "../" within $input_path? Also, what do you consider "correct chars"? I'm assuming A-Z, a-z and 0-9 are all fine. What about hyphens, underscores and spaces? Most punctuation is valid in file (and directory) names in unix and linux, but you haven't specified what operating system you're using.
if (strpos($input_path, "../") > 0) {
die("Obvious attempt to look behind the curtain");
} else
if (preg_match("/[^A-Za-z0-9_./-]/", $input_path) {
die("Illegal characters");
} else {
// do something useful
}
Salt to taste.
Note that a hyphen inside the square brackets in your regexp must be right next to the opening or closing square bracket, or must be escaped. So in a regular expression, [a-z0-9_-]
means alphanumeric plus underscore and hyphen. But [a-z0-9-_]
is an error.
Upvotes: 1