Page 1 of 1

how to serve a file only out of one directory and down

Posted: Tue Jul 25, 2006 8:31 am
by yehosef
I need to pass a filename to a script and I need that script to then do a readfile() on the file (for a Content-disposition download). I want people to only be able to access a certain subdirectory (eg "downloads") and below. There are different subdirectories beneath this so $filename includes a path:

download/goodThings/great.txt
download/betterThings/super.txt

What should I do keep people out of my ../secretThings directory?

I had tried

Code: Select all

if (ereg('\.\.', $filename))
    die('bad filename'); //die, do not process
But I don't know if that's enough.

Thank you,

Posted: Tue Jul 25, 2006 8:35 am
by feyd

Posted: Tue Jul 25, 2006 9:19 am
by Jenk

Code: Select all

//this is a 'psuedo root' - the base dir.
$ROOT_PATH = realpath('/path/to/root/');

//path to the requested file.
$path = realpath('path/to/some/file');

if ((preg_match('/^' . preg_quote($ROOT_PATH, '/') . '.*/i', $path)) && (is_file($path)) {
    readfile($path);
} else {
        die('Path to file is above root/base dir, or does not exist.');
}

what about passing as PATH_INFO?

Posted: Tue Jul 25, 2006 12:22 pm
by yehosef
If I pass the path like this

/dl.php/goodstuff/file.txt

and use the $_SERVER['PATH_INFO']

would that be ok? I tried testing it and if you put in ../../ it seems to translate it to a path in the browser.

Thanks