如何使用PHP创建zip文件

如何使用PHP创建zip文件,php,zip,Php,Zip,我正在尝试将文件从一个文件夹保存到另一个文件夹。zip文件夹放置在不同的目录中。我写了以下代码: archive.php <?php $zip = new ZipArchive(); $zip->open('example.zip', ZipArchive::CREATE); $srcDir = "/home/sam/uploads/"; $files= scandir($srcDir); //var_dump($files); un

我正在尝试将文件从一个文件夹保存到另一个文件夹。zip文件夹放置在不同的目录中。我写了以下代码:

archive.php

<?php
    $zip = new ZipArchive();
    $zip->open('example.zip',  ZipArchive::CREATE);
    $srcDir = "/home/sam/uploads/";
    $files= scandir($srcDir);
    //var_dump($files);
    unset($files[0],$files[1]);
    foreach ($files as $file) {
        $zip->addFile("{$file}");    
    }
    $zip->close();
?>


但遗憾的是,我无法创建.zip文件夹。是否有我遗漏的步骤?

请参见以下示例:

<?php
    $error = "";        //error holder
    if(isset($_POST['createpdf'])){
        $post = $_POST;     
        $file_folder = "files/";    // folder to load files
        if(extension_loaded('zip')){    // Checking ZIP extension is available
            if(isset($post['files']) and count($post['files']) > 0){    // Checking files are selected
                $zip = new ZipArchive();            // Load zip library 
                $zip_name = time().".zip";          // Zip name
                if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){       // Opening zip file to load files
                    $error .=  "* Sorry ZIP creation failed at this time<br/>";
                }
                foreach($post['files'] as $file){               
                    $zip->addFile($file_folder.$file);          // Adding files into zip
                }
                $zip->close();
                if(file_exists($zip_name)){
                    // push to download the zip
                    header('Content-type: application/zip');
                    header('Content-Disposition: attachment; filename="'.$zip_name.'"');
                    readfile($zip_name);
                    // remove zip file is exists in temp path
                    unlink($zip_name);
                }

            }else
                $error .= "* Please select file to zip <br/>";
        }else
            $error .= "* You dont have ZIP extension<br/>";
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Download As Zip</title>
</head>
<body>
<center><h1>Create Zip</h1></center>
<form name="zips" method="post">
<?php if(!empty($error)) { ?>
<p style=" border:#C10000 1px solid; background-color:#FFA8A8; color:#B00000;padding:8px; width:588px; margin:0 auto 10px;"><?php echo $error; ?></p>
<?php } ?>
<table width="600" border="1" align="center" cellpadding="10" cellspacing="0" style="border-collapse:collapse; border:#ccc 1px solid;">
  <tr>
    <td width="33" align="center">*</td>
    <td width="117" align="center">File Type</td>
    <td width="382">File Name</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" name="files[]" value="a.jpg" /></td>
    <td align="center"><img src="files/image.png" title="Image" width="16" height="16" /></td>
    <td>a.jpg</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" name="files[]" value="b.jpg" /></td>
    <td align="center"><img src="files/image.png" title="Image" width="16" height="16" /></td>
    <td>b.jpg</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" name="files[]" value="c.docx" /></td>
    <td align="center"><img src="files/doc.png" title="Document" width="16" height="16" /></td>
    <td>c.docx</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" name="files[]" value="d.pdf" /></td>
    <td align="center"><img src="files/pdf.png" title="pdf" width="16" height="16" /></td>
    <td>d.pdf</td>
  </tr>
  <tr>
    <td colspan="3" align="center">
        <input type="submit" name="createpdf" style="border:0px; background-color:#800040; color:#FFF; padding:10px; cursor:pointer; font-weight:bold; border-radius:5px;" value="Download as ZIP" />&nbsp;
        <input type="reset" name="reset" style="border:0px; background-color:#D3D3D3; color:#000; font-weight:bold; padding:10px; cursor:pointer; border-radius:5px;" value="Reset" />
    </td>
    </tr>
</table>

</form>
</body>
</html>

这里是您的项目文件夹名


您可以根据需要定义路径。

是的,我已经解决了我的问题

这里我刚刚替换了代码

$zip->addFile("{$file}");
使用代码

$zip->addFromString(basename($file),  file_get_contents($file));
完成我的工作

请尝试以下代码:

$zip = new ZipArchive;
if ($zip->open(getcwd() . '/test.zip', ZipArchive::CREATE) === TRUE) {
    $zip->addFile(getcwd() . '/file.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

创建新的zip文件

$zip=新的ZipArchive;
如果($zip->open('test_new.zip',ZipArchive::CREATE)==TRUE)
{
//将文件添加到zip文件
$zip->addFile('test.txt');
$zip->addFile('test.pdf');
//将random.txt文件添加到zip,并将其重命名为newfile.txt
$zip->addFile('random.txt','newfile.txt');
//使用指定的文本将文件new.txt文件添加到zip
$zip->addFromString('new.txt','text to add to the new.txt file');
//所有文件都已添加,因此请关闭zip文件。
$zip->close();
}
覆盖现有zip文件

$zip=新的ZipArchive;
如果($zip->open('test_overwrite.zip',ZipArchive::overwrite)==TRUE)
{
//将文件添加到zip文件
$zip->addFile('test.txt');
$zip->addFile('test.pdf');
//所有文件都已添加,因此请关闭zip文件。
$zip->close();
}

创建新的zip文件并将文件添加到文件夹中

$zip=新的ZipArchive;
如果($zip->open('test_folder.zip',ZipArchive::CREATE)==TRUE)
{
//将文件添加到demo_文件夹内的zip文件
$zip->addFile('text.txt','demo_folder/test.txt');
$zip->addFile('test.pdf','demo_folder/test.pdf');
//将random.txt文件添加到zip中,并将其重命名为newfile.txt并存储在demo_文件夹中
$zip->addFile('random.txt','demo_folder/newfile.txt');
//使用指定的文本将文件demo_folder/new.txt文件添加到zip
$zip->addFromString('demo_folder/new.txt','text to add to the new.txt file');
//所有文件都已添加,因此请关闭zip文件。
$zip->close();
}

创建一个新的zip文件并将文件移动到不同的文件夹中

$zip=新的ZipArchive;
如果($zip->open('test\u folder\u change.zip',ZipArchive::CREATE)==TRUE)
{
//将文件添加到zip文件
$zip->addFile('text.txt','demo_folder/test.txt');
$zip->addFile('test.pdf','demo_folder1/test.pdf');
//所有文件都已添加,因此请关闭zip文件。
$zip->close();
}
使用目录中的所有文件创建zip文件

$zip=新的ZipArchive;
如果($zip->open('test_dir.zip',ZipArchive::OVERWRITE)==TRUE)
{
如果($handle=opendir('demo_folder'))
{
//添加目录中的所有文件
while(false!==($entry=readdir($handle)))
{
如果($entry!=“&&$entry!=”。“&&&!is_dir('demo_folder/'.$entry))
{
$zip->addFile('demo_folder/'。$entry);
}
}
closedir($handle);
}
$zip->close();
}
将多个文件和目录添加到zip文件中

$zip=新的ZipArchive;
如果($zip->open('test\u files\u dirs.zip',ZipArchive::OVERWRITE)==TRUE)
{
//添加目录1
如果($handle=opendir('demo_folder/directory1/'))
{
while(false!==($entry=readdir($handle)))
{
如果($entry!=“&&&$entry!=”)
{
$zip->addFile('demo_folder/directory1/'。$entry);
}
}
closedir($handle);
}
//添加目录2
如果($handle=opendir('demo_folder/directory2/'))
{
while(false!==($entry=readdir($handle)))
{
如果($entry!=“&&&$entry!=”)
{
$zip->addFile('demo_folder/directory2/'。$entry);
}
}
closedir($handle);
}
//添加目录3
如果($handle=opendir('demo_folder/directory3/'))
{
while(false!==($entry=readdir($handle)))
{
如果($entry!=“&&&$entry!=”)
{
$zip->addFile('demo_folder/directory3/'。$entry);
}
}
closedir($handle);
}
//添加更多文件
$zip->addFile('demo_folder/index.txt');
$zip->close();
}
来源:

$zip->open()在成功或错误代码时返回true。所以当你与真正的用途相比===
$zip = new ZipArchive;
if ($zip->open(getcwd() . '/test.zip', ZipArchive::CREATE) === TRUE) {
    $zip->addFile(getcwd() . '/file.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
$filename = 'errors.log';
$logfile = 'path/log' . $filename;
$zipfile = date('dmY') . '.zip';
$archive = 'path/archive';
if (file_exists($logfile)) {
        $zip = new ZipArchive();
        if ($zip->open($archive . $zipfile, file_exists($archive . $zipfile) ? ZipArchive::OVERWRITE : ZipArchive::CREATE)) {
            $zip->addFile($logfile, $filename);
        }
        $zip->close();
        unlink($logfile);
    }