PHP Zip目录中的随机文件

时间:2015-11-28 20:33:02

标签: php file random zip directory

我正在创建一个网站,我正在尝试从我服务器上的文件夹(./uploads)中收集大量随机文件并压缩它们,以便用户可以下载它们。我认为我非常接近,但似乎无法正确设置循环。我试图首先使用行$files = $nfiles[array_rand($nfiles,20)];获取20个随机文件然后获取这20个文件并使用循环将它们全部压缩但我无法弄清楚如何做到这一点。 :/

编辑:发现我需要使用$rand_indexes = array_rand($nfiles, 20);而不是..现在想出如何替换glob函数来获取所有对象的列表。

<?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 = $nfiles[array_rand($nfiles,20)]; 
//-------------------------------------------//
foreach ($files as $file)
 { 
 if (!$file->isDir())
{
    // Get path for current file
    $filePath = $file->getRealPath();
    $relativePath = substr($filePath, strlen($rootPath) + 1);  
    // Add file to zip
    $zip->addFile($filePath, $relativePath);
}
 }
 //-------------------------------------------//
 $zip->close();
 header('Content-Type: application/zip');
 header('Content-disposition: attachment; filename='.'generated            
 sounds.zip');
 header('Content-Length: ' . filesize('file.zip'));
 readfile('file.zip');
  if(file_exists('file.zip')){
  unlink('file.zip');
 }
?>

1 个答案:

答案 0 :(得分:-1)

根据手册:

  

当只选择一个条目时,array_rand()返回随机条目的键。 否则,将返回随机条目的键数组

当您提取20个条目时,array_rand()的返回值是数组。因此,您需要这样做:

$files = array_rand($nfiles, 20);

foreach($files as $file) {

    $pathToFile = $nfiles[$file];

    // the rest of your code using $pathToFile

}