使用PHP ZipArchive下载多个文件

时间:2015-11-30 16:33:32

标签: php php-zip-archive

我正在尝试随机下载一些文件。

我道歉,因为我之前发布过,但有人可以解释一下我做错了什么吗?

我似乎无法调试它,因为我知道最小的PHP。

<?php 
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);     
$files = array_rand($nfiles, 20);
foreach($files as $file)  {
    $pathtofile = $nfiles[$file];
    if (!$file->isDir())
    {
        // Get path for current file
        $filePath = $pathtofile->getRealPath();
        $relativePath = str_replace($rootPath, "", $file);
        // Add file to zip
        $zip->addFile($filePath, $relativePath);
    }
}
//-------------------------------------------//
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment;
filename='.'generatedsounds.zip');
header('Content-Length: ' . filesize('file.zip'));
readfile('file.zip');
if(file_exists('file.zip'))
{
    unlink('file.zip');
}
?>

1 个答案:

答案 0 :(得分:0)

您正在调用未定义的->isDir()方法,并且您正在调用也未定义的->getRealPath()

然后你获取所有文件然后从数组中选择20个随机文件(为什么??)

当您重写标题时,错误不会显示在浏览器中,尝试不重写标题,这意味着它保留为html标题并进行测试,直到您获得二进制文件输出然后添加标题所以你有一个工作代码。