I am trying to make a script that will let me download files outside my web root directory and list the files…It is listing the files of the directory but it does not allow me to download them as when they are clicked it just goes to website.com/clickedlink.jpg but it needs to some how change that to go to the location I would like…
I think I am explaining this a little odd so please tell me if it needs clarification.
I need to download files from /home/files/I/need but the website is stored in /var/website/
so if someone could please help out I’d be 100% thankful!
<html><head><title>Root page</title></head><body>
<?
// open this directory
$myDirectory = opendir("/home/files/I/need");
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");
// sort 'em
sort($dirArray);
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
print("<td>");
print(filetype($dirArray[$index]));
print("</td>");
print("<td>");
print(filesize($dirArray[$index]));
print("</td>");
print("</TR>\n");
}
}
print("</TABLE>\n");
?>
</body></html>
</body></html>
The best solution is to let your web server take care of this by creating a location alias; having the web server perform the downloading for you is much more scalable than doing this in PHP.
However, since you asked for a PHP solution, add this to this top of your script:
To construct the URL to make the download:
The
/path/to/your/script.phpis the same URL that generates the page; you append a slash, together with the intended filename.I’m using
basename()to prevent people from accessing../../../etc/passwdor some other file they shouldn’t be seeing, but that also means you can’t use sub folders. If you need to support sub folders, you have to sanitize thePATH_INFOin a different manner.