Prevent Parent Directory in php directory listing program

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
unplugme71
Forum Newbie
Posts: 13
Joined: Wed Jul 13, 2011 2:39 pm

Prevent Parent Directory in php directory listing program

Post 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!
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Prevent Parent Directory in php directory listing progra

Post by McInfo »

unplugme71
Forum Newbie
Posts: 13
Joined: Wed Jul 13, 2011 2:39 pm

Re: Prevent Parent Directory in php directory listing progra

Post 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.
unplugme71
Forum Newbie
Posts: 13
Joined: Wed Jul 13, 2011 2:39 pm

Re: Prevent Parent Directory in php directory listing progra

Post by unplugme71 »

anyone else have other suggestions?
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Prevent Parent Directory in php directory listing progra

Post 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
}
Post Reply