[英]Download all Files in a Directory from my Website into a Zip Folder
所有,我允许用户将图像上传到我的网站。 对于该用户,我想下载该用户从我的网站上传到我的网站的所有图像。 因此,我希望基本上有一个用户名下拉列表,然后当我选择一个查询我的数据库并获取他们下载的所有图像时。 那部分没问题。
我的问题是,如何浏览每个文件并将它们放入zip文件夹,然后下载zip文件夹(如果可能)。
关于如何做这样的事情有什么想法吗?
提前致谢!
编辑:我知道如何使用以下代码将文件压缩后下载:
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=filename.zip');
header('Content-Length: ' . filesize($zipfilename));
readfile($zipname);
感谢@maxhud的帮助,我得以提出完整的解决方案。 这是用于实现我期望的结果的最终代码段:
<?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(
'upload/1_3266_671641323389_14800358_42187034_1524052_n.jpg', 'upload/1_3266_671641328379_14800358_42187035_3071342_n.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);
}
?>
一个PHP命令,可让您运行系统命令
AND系统命令,例如
通常更有效。
我个人的EX创建文件系统的备份并覆盖以前的备份
$uploads = wp_upload_dir();
$file_name = 'backup_filesystem.tar.gz';
unlink($uploads['basedir'] . '/' . $file_name);
ob_start();
$output = shell_exec(sprintf('tar -zcvf %s/%s %s', $uploads['basedir'], $file_name, ABSPATH));
ob_end_clean();
注意:输出缓冲区,以防您的php to shell命令有输出并且您不希望头文件已发送错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.