I am currently making a website and I am trying to collect a number of random files from a folder on my server (./uploads) and zip them so the user can download them. I think I am pretty close but cant seem to setup the loop right. I am trying to first get 20 random files with the line $files = $nfiles[array_rand($nfiles,20)];
then take these 20 files and use the loop to zip them all up but I can not figure out quite how to do it. :/
edit: discovered that i need to use $rand_indexes = array_rand($nfiles, 20);
instead..now to figure out how to replace the glob function to just get a list of all objects.
<?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');
}
?>
Aucun commentaire:
Enregistrer un commentaire