51

I am trying to save files from one folder to another. zip folder placed in different directory. And I have written the following codes:

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();
?>

But sadly I am not able to create the .zip folder. Is there any step I missed?

Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
Sam
  • 1,033
  • 3
  • 16
  • 25

6 Answers6

45
$zip = new ZipArchive();

$DelFilePath="first.zip";

if(file_exists($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath)) {

        unlink ($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath); 

}
if ($zip->open($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
        die ("Could not open archive");
}
    $zip->addFile("file_path","file_name");

// close and save archive

$zip->close(); 

Here TEST is your project folder name.

You can define path as you want.

Dhruvisha
  • 2,538
  • 1
  • 21
  • 31
21

Create a new zip file

$zip = new ZipArchive;
if ($zip->open('test_new.zip', ZipArchive::CREATE) === TRUE)
{
    // Add files to the zip file
    $zip->addFile('test.txt');
    $zip->addFile('test.pdf');
 
    // Add random.txt file to zip and rename it to newfile.txt
    $zip->addFile('random.txt', 'newfile.txt');
 
    // Add a file new.txt file to zip using the text specified
    $zip->addFromString('new.txt', 'text to be added to the new.txt file');
 
    // All files are added, so close the zip file.
    $zip->close();
}

Overwrite an existing zip file

(When using OVERWRITE, the file must already exist. If it doesn't exist yet, the operation will fail.)

$zip = new ZipArchive;
if ($zip->open('test_overwrite.zip', ZipArchive::OVERWRITE) === TRUE)
{
    // Add file to the zip file
    $zip->addFile('test.txt');
    $zip->addFile('test.pdf');
 
    // All files are added, so close the zip file.
    $zip->close();
}

Create a new zip file and add files to be inside a folder

$zip = new ZipArchive;
if ($zip->open('test_folder.zip', ZipArchive::CREATE) === TRUE)
{
    // Add files to the zip file inside demo_folder
    $zip->addFile('text.txt', 'demo_folder/test.txt');
    $zip->addFile('test.pdf', 'demo_folder/test.pdf');
 
    // Add random.txt file to zip and rename it to newfile.txt and store in demo_folder
    $zip->addFile('random.txt', 'demo_folder/newfile.txt');
 
    // Add a file demo_folder/new.txt file to zip using the text specified
    $zip->addFromString('demo_folder/new.txt', 'text to be added to the new.txt file');
 
    // All files are added, so close the zip file.
    $zip->close();
}

Create a new zip file and move the files to be in different folders

$zip = new ZipArchive;
if ($zip->open('test_folder_change.zip', ZipArchive::CREATE) === TRUE)
{
    // Add files to the zip file
    $zip->addFile('text.txt', 'demo_folder/test.txt');
    $zip->addFile('test.pdf', 'demo_folder1/test.pdf');
 
    // All files are added, so close the zip file.
    $zip->close();
}

Create a zip file with all files from a directory

$zip = new ZipArchive;
if ($zip->open('test_dir.zip', ZipArchive::OVERWRITE) === TRUE)
{
    if ($handle = opendir('demo_folder'))
    {
        // Add all files inside the directory
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != ".." && !is_dir('demo_folder/' . $entry))
            {
                $zip->addFile('demo_folder/' . $entry);
            }
        }
        closedir($handle);
    }
 
    $zip->close();
}

Add multiple files and directories to a zip file

$zip = new ZipArchive;
if ($zip->open('test_files_dirs.zip', ZipArchive::OVERWRITE) === TRUE)
{
    // Add directory1
    if ($handle = opendir('demo_folder/directory1/'))
    {
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != "..")
            {
                $zip->addFile('demo_folder/directory1/' . $entry);
            }
        }
        closedir($handle);
    }
 
    // Add directory2
    if ($handle = opendir('demo_folder/directory2/'))
    {
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != "..")
            {
                $zip->addFile('demo_folder/directory2/' . $entry);
            }
        }
        closedir($handle);
    }
 
    // Add directory3
    if ($handle = opendir('demo_folder/directory3/'))
    {
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != "..")
            {
                $zip->addFile('demo_folder/directory3/' . $entry);
            }
        }
        closedir($handle);
    }
 
    // Add more files
    $zip->addFile('demo_folder/index.txt');
 
    $zip->close();
}

Source: https://www.virendrachandak.com/techtalk/how-to-create-a-zip-file-using-php/

Richard
  • 1,912
  • 20
  • 28
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
20

Yes I have solved my problem .

Here I have just replaced the code

$zip->addFile("{$file}");

with the code

$zip->addFromString(basename($file),  file_get_contents($file));

and get my work done. :)

Sam
  • 1,033
  • 3
  • 16
  • 25
8

Try this code:

$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';
}
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
Indrajeet Singh
  • 2,958
  • 25
  • 25
4

Please see this below example:

<?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>
youeye
  • 737
  • 1
  • 7
  • 31
2
$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);
    }
gjerich
  • 369
  • 3
  • 6