我使用下面的代码从文件夹根目录中的所有文件中创建和下载一个 zip 文件。我有这条线
$files_to_zip = array(
'room1.jpg', 'room2.jpg'
);
它使您可以选择将哪些文件放入 zip 文件中 - 但我的文件是 cron 作业的结果,因此每天都会生成一个新文件。我如何编写一个变量来表示除“”之外的所有文件,然后在 zipfolder 中列出我不想要的文件,即。index.php 等
到目前为止,我尝试编写$files_to_zip = *;
(显然不会排除任何文件),但这只会引发Parse 错误:语法错误
这是下面的完整代码:
<?php
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = true) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
$files_to_zip = array(
'room1.jpg', 'room2.jpg'
);
//if true, good; if false, zip creation failed
$zip_name = 'my-archive.zip';
$result = create_zip($files_to_zip,$zip_name);
if($result){
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=filename.zip');
header('Content-Length: ' . filesize($zip_name));
readfile($zip_name);
}
?>