Page 1 of 1

Prevent Parent Directory in php directory listing program

Posted: Tue Aug 30, 2011 2:33 pm
by unplugme71
I created a script to show all folders and files.

There is a variable called

$rootdir = "/path/to/root/directory";

$rootdir is the lowest directory the software should list folder contents.

However, if you did http://example.com/?dir=/../ it would show /path/to/root

How can I write a check that prevents anyone from going past $rootdir?

Thanks!

Re: Prevent Parent Directory in php directory listing progra

Posted: Tue Aug 30, 2011 7:36 pm
by McInfo

Re: Prevent Parent Directory in php directory listing progra

Posted: Tue Aug 30, 2011 10:22 pm
by unplugme71
I couldn't get it to work with my script. That or I'm unsure how to use it to verify that they aren't going up a directory beyond what they are allowed.

Re: Prevent Parent Directory in php directory listing progra

Posted: Wed Aug 31, 2011 9:33 am
by unplugme71
anyone else have other suggestions?

Re: Prevent Parent Directory in php directory listing progra

Posted: Wed Aug 31, 2011 9:10 pm
by McInfo

Code: Select all

$rootdir = '/path/to/root/directory';
// User input
$input = '/../';
// Forces the input string to begin with a slash, to prevent access to parallel directories
$input = '/' . ltrim($input, '/');
// Full path, pending validation
$path = realpath($rootdir . $input);
// Checks if the path begins with the root path. The choice of comparison operator is important.
if (strpos($path, $rootdir) === 0) {
    // Okay
}