【发布时间】:2013-08-17 18:22:30
【问题描述】:
我正在使用下面的 php 文件代码列出目录中的文件,用户将从该目录中检查所需文件并将它们下载为 zip 文件
我有两个问题
1) 如何使用 url 保护文件不被直接下载
2) 此代码还在列表中显示 .htaccess 以供下载(所以我怀疑他们是只列出 Docs、xls、pdf 的一种方式)
如果需要,我可以提供 downloadlist.php
<?php
function listDir($dirName)
{
?><form name="filelist" action="downloadList.php" method="POST"><?php echo "\n";
if ($handle = opendir($dirName)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") { ?> <input type=checkbox name="file[]" value="<?php echo "$file";?>"><?php echo "$file"; ?><br><?php echo "\n";
}
}
closedir($handle);
}
?><br><input type="submit" name="formSubmit" value="Zip and download" /></form><?php
}
listDir('./fold'); ?>
下载列表.php
<?php
// function download($file) downloads file provided in $file
function download($file) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
$files = $_POST['file'];
if(empty($files))
{
echo("You haven't selected any file to download.");
}
else
{
$zip = new ZipArchive();
$filename = time() . "archive.zip"; //adds timestamp to zip archive so every file has unique filename
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { // creates new zip archive
exit("Cannot open <$filename>\n");
}
$N = count($files);
for($i=0; $i < $N; $i++)
{
$zip->addFile($files[$i], $files[$i]); //add files to archive
}
$numFiles = $zip->numFiles;
$zip->close();
$time = 8; //how long in seconds do we wait for files to be archived.
$found = false;
for($i=0; $i<$time; $i++){
if($numFiles == $N){ // check if number of files in zip archive equals number of checked files
download($filename);
$found = true;
break;
}
sleep(1); // if not found wait one second before continue looping
}
if($found) { }
else echo "Sorry, this is taking too long";
} ?>
【问题讨论】:
-
你能提供我你的 downloadlist.php 文件吗?
-
@undone 添加了 downloadlist.php 请检查
-
对不起,某个白痴切断了我家的电话线,只好等待修好!