How to build a file path using php?

I have a directory and a dynamic file name. Are there any functions that I can use to make sure that it is impossible to break out of the specified directory?

eg:

secure_path('/tmp/', 'file.txt') -> /tmp/file.txt secure_path('/tmp/', '../file.txt') -> /tmp/file.txt 
+4
source share
3 answers

If you work in only one directory and not the subdirectories below, you can do

 $file = "/tmp/".basename($input); 

Which should give you the file name at the end of any path specified in the input, and add it to the directory you need.

+2
source

Use realpath() to get the canonical form of the path, and eliminate any ../ -s. Then make sure that it contains the full path to the directory in which you want to contain it.

For instance:

 $path = "/tmp/file.txt"; $directory = "{full path of your files directory}"; if (strpos(realpath($path), $directory) === 0) { // path OK } else { // path not ok } 
+2
source

I really don't know how ../file.txt should turn into /tmp/file.txt in your example, but to check if the path is an approach to another, use realpath with a simple comparison:

 $path = '../foo'; $allowedPath = '/tmp/'; $path = realpath($path); if (substr($path, 0, strlen($allowedPath)) !== $allowedPath) { // path is not within allowed path! } 
0
source

Source: https://habr.com/ru/post/1346343/


All Articles