2

I need to validate passed file path, before it will be written to disk and new directory structure for it will be created. For example, we have $path = "/uploads/base/../../user_new_dir/img.jpg". This is incorrect path due to "/.." ("/uploads/base" - allowed for saving directory, "/user_new_dir/img.jpg" - user defined path and file name).

I can't use realpath($path), because it works only with existing files. I can't use realpath(dirname($path)), because we may create new folders for saving file.

I look for script, which checks all possible cases. I worry that I can miss something like multi-byte representation of the '.' character or others unexpected ways, which may cause security issues. Could you advice appropriate implementation of my task in any framework or cms, so I could look into it?

laxonline
  • 2,657
  • 1
  • 20
  • 37
  • 1
    Why are users passing file paths? – Waleed Khan Jan 13 '13 at 04:01
  • 2
    Best way: do not write files based on user supplied information. Make up your own random file names. – deceze Jan 13 '13 at 04:01
  • @deceze - Also has the advantage on not inadvertently enabling users to overwrite files. – Ed Heal Jan 13 '13 at 04:04
  • Why not just check for `..` in the string? – Petah Jan 13 '13 at 04:06
  • This is made for private administrator part, so we could save uploaded files not at web-server local filesystem, but we would send them to master server. Because of this, we need to support variable directory structure. There are other protection like allowed IPs and check of allowed for uploading folders. – тараканы_простыли Jan 13 '13 at 04:08
  • possible duplicate of [Replace PHP's realpath()](http://stackoverflow.com/questions/4049856/replace-phps-realpath) – idmean Sep 04 '14 at 08:47

1 Answers1

2

Check out this one: https://stackoverflow.com/a/4050444/108544

That function operates on the path string, and should also work if the target path doesn't actually exist on the file system.

Community
  • 1
  • 1
jmc
  • 540
  • 3
  • 11