I want to test if a path given by the user go down like:
my/down/path
at the opposite of:
this/path/../../go/up
for security reasons.
I already made this:
return (bool)preg_match('#^([a-z0-9_-])+(\/[a-z0-9_-])*$#i', $fieldValue);
But the user should be allowed to use the '.' in his path (like: my/./path, that not useful but he can) and I don’t know how to consider it.
I’m then looking for a secure regex to check this.
Thanks
edit: After viewing answers, yes it would be fine if the test check if the real path (removing '.' and '..') is a down path.
You probably do not want to check that a path doesn’t contain
..but instead want to check that if evaluated as whole, it doesn’t go up. E.g../path/..is still in., even though it contains...You can find an implementation of path depth validation in Twig:
Twig does not use
realpathfor the validation, becauserealpathhas issues with paths in Phar archives. Additionallyrealpathonly works if the pathname already exists.