简体   繁体   中英

Downloading multiple files using PHP ZipArchive

I am trying to randomly download some files.

I apologize because I posted it earlier but can someone explain what I am doing wrong in detail?

I can not seem to debug it as I know minimal 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');
}
?>

You're calling ->isDir() method which is not defined, And you're calling ->getRealPath() which is also not defined.

And you're getting all files then selecting 20 random files from the array (why??)

While you are rewriting the headers, errors won't be shown in browser, try without rewriting headers which means it's kept as html header and test until you get a binary file output then add the headers back so you have a working code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM