Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP压缩目录中的随机文件_Php_File_Random_Zip_Directory - Fatal编程技术网

PHP压缩目录中的随机文件

PHP压缩目录中的随机文件,php,file,random,zip,directory,Php,File,Random,Zip,Directory,我目前正在制作一个网站,我试图从我服务器上的文件夹中收集一些随机文件(/上传),并将其压缩,以便用户可以下载。我想我已经很接近了,但似乎无法正确设置循环。我试图首先得到20个随机文件,行为$files=$nfiles[array_rand($nfiles,20)]然后将这20个文件全部压缩,但我不知道怎么做:/ 编辑:发现我需要使用$rand\u index=array\u rand($nfiles,20)

我目前正在制作一个网站,我试图从我服务器上的文件夹中收集一些随机文件(/上传),并将其压缩,以便用户可以下载。我想我已经很接近了,但似乎无法正确设置循环。我试图首先得到20个随机文件,行为
$files=$nfiles[array_rand($nfiles,20)]
然后将这20个文件全部压缩,但我不知道怎么做:/

编辑:发现我需要使用
$rand\u index=array\u rand($nfiles,20)
<?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');
 }
?>

根据手册:

仅拾取一个条目时,array_rand()返回随机条目的键否则,将返回随机项的键数组

在获取
20
条目时,
array\u rand()
的返回值是一个数组。因此,您需要这样做:

$files = array_rand($nfiles, 20);

foreach($files as $file) {

    $pathToFile = $nfiles[$file];

    // the rest of your code using $pathToFile

}

好的,我这样做了,但仍然得到一个奇怪的错误,说503后端提取失败<代码>$nfiles=glob($rootPath.*.{aiff}',glob_括号)$files=array_rand($n文件,20);foreach($file作为$file){if(!$file->isDir()){//Get当前文件的路径$pathtofile=$nfiles[$file]$filePath=$pathtofile->getRealPath();
您需要在
foreach($file作为$file){
之后执行
操作。