我创建了一个脚本来上传照片并将不同尺寸的版本放入文件夹中。之后,我想要压缩该文件夹。除了压缩文件之外,脚本正在完成我想要的所有工作。没有出现错误。
以下是代码:
session_start();
$_SESSION['upload_time']=time();
$target_dir = 'downloads/'.$_FILES['userImage']["name"].'-'.$_SESSION['upload_time'].'/';
if(!is_dir($target_dir)){
mkdir($target_dir);
}
$file4 = file_get_contents('assets/sizes.txt', true);
$data4=json_decode($file4,true);
foreach($data4 as $data){
$data=explode('_',$data);
$data1= preg_replace("/[^0-9]/","",$data[0]);
$data2= preg_replace("/[^0-9]/","",$data[1]);
///uploading photo and creating its different sizes
store_uploaded_image('userImage',$data1,$data2,$data1.'x'.$data2 ,$target_dir);
}
$zip = new ZipArchive();
// open archive
if ($zip->open('my-archive.zip', ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive");
}
// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($target_dir));
// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value) {
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
// close and save archive
$zip->close();
echo "Archive created successfully.";
答案 0 :(得分:0)
尝试此代码,对于本地系统,您可以使用此代码压缩特定文件夹。
<强>代码: - 强>
<?php
function Zip($source, $destination)
{
echo "called function";
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
Zip('/downloads','/my-archive.zip',true);
?>
希望这有帮助。