prasathmani / tinyfilemanager

Single-file PHP file manager, browser and manage your files efficiently and easily with tinyfilemanager
https://tinyfilemanager.github.io
GNU General Public License v3.0
5.02k stars 1.68k forks source link

Feature request - set $root_path and $root_url from $_SERVER['REQUEST_URI'] #1251

Open devnull4242 opened 1 week ago

devnull4242 commented 1 week ago

Tiny File Manager is very cool. Thanks.

Unfortunately, in many cases it is necessary to adjust the variables $root_path and $root_url within the code. This is due to the use of subdirectories. Even calling the same file https://domain.tld/subdomain/tinyfilemanager.php or https://subdomain.domain.tld/tinymfilemanager.php leads to side effects and therefore to security problems under certain circumstances.

I would therefore like to suggest automatically extending the values of $root_path and $root_url via $_SERVER['REQUEST_URI'] in such a way that it works for directories and subdirectories as well as for rewrites from e.g. tinyfilemanager.php to /admin. I think than it works in the most cases without modifications in the code.

function extractBasePath($requestUri) {
    $path = preg_replace('/[?#].*$/', '', $requestUri);
    $path = urldecode($path);
    $path = '/' . trim($path, '/');
    $path = preg_replace('|/+|', '/', $path);
    $lastSlashPosition = strrpos($path, '/');

    if ($lastSlashPosition === false || $lastSlashPosition === 0) {
        return '/';
    }
    return substr($path, 0, $lastSlashPosition);
}

$base_path = extractBasePath($_SERVER['REQUEST_URI']);

$base_path is the folder /path or /path1/path2 ... where the phpfilemanager.php is located. From the point of view of PHP File Manager it is /. If phpfilemanager.php is located in a subdirectory and you want to access directories above it, you would have to set $base_path once manually. $base_path='';

// Root path for file manager
// use absolute path of directory i.e: '/var/www/folder' or $_SERVER['DOCUMENT_ROOT'].'/folder'
//make sure update $root_url in next section
$root_path = $_SERVER['DOCUMENT_ROOT'] . $base_path;

// Root url for links in file manager.Relative to $http_host. Variants: '', 'path/to/subfolder'
// Will not working if $root_path will be outside of server document root
$root_url = $base_path;

You could also dispense with $base_path in the implementation and just use the variable $root_url.