PHP压缩目录中的随机文件
我目前正在制作一个网站,我试图从我服务器上的文件夹中收集一些随机文件(/上传),并将其压缩,以便用户可以下载。我想我已经很接近了,但似乎无法正确设置循环。我试图首先得到20个随机文件,行为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)
$files=$nfiles[array_rand($nfiles,20)]
然后将这20个文件全部压缩,但我不知道怎么做:/
编辑:发现我需要使用$rand\u index=array\u 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');
}
?>
根据手册:
仅拾取一个条目时,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){
之后执行操作。