我正在尝试制作一个脚本,让我可以在我的 Web 根目录之外下载文件并列出文件......它列出了目录的文件,但它不允许我下载它们,因为当它们被单击时,它只是转到 website.com/clickedlink.jpg 但它需要一些如何更改才能转到我想要的位置......
我想我解释这一点有点奇怪,所以请告诉我是否需要澄清。
我需要从/home/files/I/need 下载文件,但网站存储在/var/website/
所以如果有人能帮忙,我会100%感激!
<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>
最好的解决方案是通过创建位置别名来让您的 Web 服务器来处理这个问题;让 Web 服务器为您执行下载比在 PHP 中执行此操作更具可扩展性。
但是,由于您要求PHP解决方案,因此请将其添加到脚本的顶部:
$basePath = "/home/files/I/need";
if (isset($_SERVER['PATH_INFO']) && $file = basename($_SERVER['PATH_INFO'])) {
if (file_exists("$basePath/$file")) {
// add file size
header('Content-Length: ' . filesize("$basePath/$file"));
// write file to output
readfile("$basePath/$file");
return;
}
}
要构造用于下载的 URL,请执行以下操作:
/path/to/your/script.php/clickedlink.jpg
/path/to/your/script.php
是生成页面的同一 URL;您可以附加一个斜杠以及预期的文件名。
我正在使用basename()
来防止人们访问他们不应该看到的../../../etc/passwd
或其他文件,但这也意味着您不能使用子文件夹。如果需要支持子文件夹,则必须以不同的方式清理PATH_INFO
。