你好,我用這個函數創建一個zip文件(子文件和子目錄)遞歸函數來創建一個zip文件
<?php
function folderToZip($folder, &$zipFile, $exclusiveLength) {
$handle = opendir($folder);
while (false !== $f = readdir($handle)) {
if ($f != '.' && $f != '..') {
$filePath = "$folder/$f";
// Remove prefix from file path before add to zip.
$localPath = substr($filePath, $exclusiveLength);
if (is_file($filePath)) {
$zipFile->addFile($filePath, $localPath);
} elseif (is_dir($filePath)) {
// Add sub-directory.
$zipFile->addEmptyDir($localPath);
folderToZip($filePath, $zipFile, $exclusiveLength);
}
}
}
closedir($handle);
}
function zipDir($sourcePath, $outZipPath)
{
$pathInfo = pathInfo($sourcePath);
$parentPath = $pathInfo['dirname'];
$dirName = $pathInfo['basename'];
$z = new ZipArchive();
$z->open($outZipPath, ZIPARCHIVE::CREATE);
//$z->addEmptyDir($dirName);
folderToZip($sourcePath, $z, strlen("$parentPath/"));
$z->close();
}
zipDir('mydirectory', 'copy_'.time().'.zip');
?>
功能完美的作品,但只有當文件創建的.zip文件是外部 「mydirectory中」
- mydirectory
- createzip.php
但我想創建的.zip文件是 「mydirectory中/更新/」
文件- mydirectory
- mydirectory/update/createzip.php
,並做到這一點:zipDir('../../mydirectory', 'copy_'.time().'.zip');
,但這不起作用
UPDATE:使用此功能,問題仍然存在,我無法通過運行腳本從文件夾複製使該文件夾的副本要複製
function Zip($source, $destination)
{
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文件,然後只需使用'copy($ file,$ newfile)'將文件移動到您想要的位置 –
問題是腳本不起作用,如果文件createzip.php)在mydirectory/update /裏面,我需要那個文件仍然在裏面 – WhiteLine