Create Zip Archive File With PHP

Create Zip Archive File With PHP

Zip is a file format for data compression and as a standard format, zip is a file archive, the use zip archives is to compress many files or large files so that the file size becomes small and can save storage media and more efficient in file transfers or send files . It would be more difficult to transfer data if without using zip archives, because if sending large files takes large media storage space and takes a long time to file transfer process.

In addition, zip archives are also resistant to viruses that can damage the files in it, mostly due to the virus attack the affected zip file but the file there still survived, there is also a case of files in the zip archive has a virus but our computer stays safe if Does not run files in zip archives that are exposed to viruses.

Doing compression of many files or large files using zip archives is the right solution for manual data transfer such as using flash, data cable/lan, infrared or by using wireless and bluetooth. The compressed files remain safe from virus attacks, so it’s very safe and easy to use.

Next is how to create a zip file using php and how to read a zip file in the browser. How to create zip archives using php is like the explanation below.

Library for Layout Design

We need a template library to design the layout, we can use popular libraries like Bootstrap, Awesome Fonts, and DataTables, in addition you can also use Metro UI CSS, UIKit, W3CSS, MaterializeCSS and others. Below is a library that will be used to create a layout for zip archives with php.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script>
    $('table').dataTable();
</script>

Create Zip Archive File

Creating a zip file using php, here is not just one file that can be compressed into zip archives but also we can add folders or multiple files at once into the zip archive. To create a zip file, first create a design input form for the name of the zip file and the source of the folder or file, as below.

<form method="post">
    <div class="form-group">
        <label for="na">Name Archive</label>
        <div class="input-group">
           <input type="text" class="form-control" id="na" name="na" placeholder="phptoziparchiver" aria-describedby="basic-addon2">
           <span class="input-group-addon" id="basic-addon2">.zip</span>
        </div>
    </div>
    <div class="form-group">
        <label for="sr">Source</label>
        <input type="text" class="form-control" id="sr" name="sr" placeholder="C:\xampp\htdocs\project\phptoziparchiver"/>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block" id="an" name="an"/><i class="fa fa-plus"></i> Create New Archive</button>
   </div>
</form>

Make a folder to save the zip file, then make the execution of both form input using php, in order to compress the file or folder into the zip file automatically and save it into the folder that was created earlier. For the command code as below.

if(isset($_POST['an'])){
       $sr = $_POST['sr'];
       $na = $_POST['na'];
       $source = $sr;
       $filename = $na.".zip";
       class CustomArchive extends ZipArchive {
                public function addDir($location, $name) {
                    $this->addEmptyDir($name);
                    $this->addDirDo($location, $name);
                }
                private function addDirDo($location, $name) {
                    $name .= '/';         
                    $location .= '/';
                    $dir = opendir ($location);
                    while ($file = readdir($dir))    {
                        if ($file == '.' || $file == '..') continue;
                            $do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
                            $this->$do($location . $file, $name . $file);
                    }
                } 
       }

       $zip = new CustomArchive;
       $res = $zip->open("./archives/".$filename, ZipArchive::CREATE);
       if($res === TRUE)    {
           $zip->addDir($source, basename($source)); $zip->close();
       } else  { 
           echo 'Could not create a zip archive';
       }
}

Read File From Directory

Reading files from the zip file storage directory created using php, the function to make it easier for us to open zip files and view the contents in zip files, and with files that have been read in the browser can create a function to delete, add files or folder, create a password and etc.

Files that have been read from the directory will be displayed into a list containing the link address leading to the zip file open and link to remove the zip file from list and directory. To make it as below.

<ul class="list-group">
    <?php
         if ($handle = opendir('./archives')) {
             while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
    ?>
                        <li class='list-group-item'>
                            <span onclick="window.location.href='?delfile=<?php echo $entry ?>'" class='badge'><i class='fa fa-trash'></i></span>
                            <a href='archiver.php?file=<?php echo $entry ?>'><?php echo $entry ?></a>
                        </li>
    <?php
                     }
             }
             closedir($handle);
         }
    ?>
</ul>

Remove File From Directory

Deleting files from directories and lists is necessary to remove unnecessary files in the directory but can also remove manuals in the directory by using Explorer on both Windows and Ubuntu / Mac OS X, for the syntax code as below.

<a href='archiver.php?file=<?php echo $entry ?>'><?php echo $entry ?></a>

<?php
if(isset($_GET['delfile'])){
       if(unlink('./archives/'.$_GET['delfile'])){
              echo "<script>location.href='index.php'</script>";
       }
}
?>

Open Zip Archive File

Open the zip archive file into the table using php, The contents of the zip archive file will be displayed into the table along with the root of the existing folder in the zip file as the example “text.txt file in the docs folder” it will be displayed to “docs/text.txt” On the table item. To syntax the table with php as below.

<table class="table table-striped table-hover">
    <thead>
         <tr>
             <th>File Name</th>
             <th>File Size</th>
             <th>Compressed Size</th>
             <th>Compression Method</th>
             <th>Action</th> 
         </tr>
    </thead>
    <tbody>
         <?php
         $za = zip_open('./archives/'.$zip);
         if ($za) {
               while ($zip_entry = zip_read($za)) {
         ?>
            <tr>
                 <td><?php echo $fn = zip_entry_name($zip_entry) ?></td>
                 <td><?php echo zip_entry_filesize($zip_entry) ?></td>
                 <td><?php echo zip_entry_compressedsize($zip_entry) ?></td>
                 <td><?php echo zip_entry_compressionmethod($zip_entry) ?></td>
                 <td>
                     <a target="_blank" href="function.php?file=<?php echo $zip ?>&exec=viewfile&src=<?php echo $fn ?>"><i class="fa fa-eye"></i></a> &nbsp;
                     <a href="function.php?file=<?php echo $zip ?>&exec=delfile&src=<?php echo $fn ?>"><i class="fa fa-trash"></i></a>
                 </td>
             </tr>
          <?php
               }
          }
          ?>
     </tbody>
</table>

Add New File and Create New Folder

Add a new file and create a new folder into an existing zip file. Can add files or create folders into zip files using php, Create an input form to add files and input form to create a folder, can also form created in the modal dialog, as below.

<button type="button" data-toggle="modal" data-target="#myModal-addfile" class="btn btn-primary"><i class="fa fa-file-o"></i> Add File</button>
<button type="button" data-toggle="modal" data-target="#myModal-addfolder" class="btn btn-success"><i class="fa fa-folder"></i> Add Folder</button>

<!-- Modal addfile -->
        <div class="modal fade" id="myModal-addfile" tabindex="-1" role="dialog" aria-labelledby="myModaladdfile">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModaladdfile">Add File</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="addfile"/>
                    <div class="form-group">
                        <input type="text" name="des" class="form-control" placeholder="Add New File or Destination File"/>
                    </div>
                    <div class="form-group">
                        <input type="text" name="src" class="form-control" placeholder="Source New File"/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
        </div>
        <!-- Modal addfolder -->
        <div class="modal fade" id="myModal-addfolder" tabindex="-1" role="dialog" aria-labelledby="myModaladdfolder">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModaladdfolder">Add Folder</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="addfolder"/>
                    <div class="form-group">
                        <input type="text" name="src" class="form-control" placeholder="Add New Folder"/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
</div>

Code execution command syntax to add new file and create new folder using php as below.

$zip = new ZipArchive;
$file = isset($_GET['file'])? $_GET['file'] : '';
$exec = isset($_GET['exec'])? $_GET['exec'] : '';
$src = isset($_GET['src'])? $_GET['src'] : '';
$des = isset($_GET['des'])? $_GET['des'] : '';
$res = $zip->open('./archives/'.$file);
if($exec == 'addfile'){
    if($zip->addFile($src, $des)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'addfolder'){
    if($zip->addEmptyDir($src)) {
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
}

Extract to, Set Password, Comment and Download

Extract to is a function to extract existing files in a zip archive into another directory. Commonly called uncompress, set password is to provide a password for the zip file, comment is to comment for the zip file and download is get the zip file.

<button type="button" data-toggle="modal" data-target="#myModal-extracto" class="btn btn-warning"><i class="fa fa-file-archive-o"></i> Extract to</button>
<button type="button" data-toggle="modal" data-target="#myModal-setpassword" class="btn btn-danger"><i class="fa fa-key"></i> Set Password</button>
<button type="button" data-toggle="modal" data-target="#myModal-comment" class="btn btn-default"><i class="fa fa-comment"></i> Comment</button>
<a href="./archives/<?php echo $zip ?>" class="btn btn-info"><i class="fa fa-download"></i> Download</a>

<!-- Modal extracto -->
        <div class="modal fade" id="myModal-extracto" tabindex="-1" role="dialog" aria-labelledby="myModalextracto">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalextracto">Extract to</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="extracto"/>
                    <div class="form-group">
                        <input type="text" name="src" class="form-control" placeholder="Extract to ..."/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
        </div>
        <!-- Modal password -->
        <div class="modal fade" id="myModal-setpassword" tabindex="-1" role="dialog" aria-labelledby="myModalsetpassword">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalsetpassword">Set Password</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="setpassword"/>
                    <div class="form-group">
                        <input type="password" name="src" class="form-control" placeholder="Set Password"/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
        </div>
        <!-- Modal comment -->
        <div class="modal fade" id="myModal-comment" tabindex="-1" role="dialog" aria-labelledby="myModalcomment">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalcomment">Comment</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="comment"/>
                    <div class="form-group">
                        <textarea name="src" class="form-control" placeholder="Add Comment"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
</div>

Next make execution for Extract to, Set Password, Command and Download using php, like syntax code below.

else if($exec == 'extracto'){
    if($zip->extractTo($src)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'setpassword'){
    if($zip->setPassword($src)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'comment'){
    if($zip->setArchiveComment($src)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'viewfile'){
    echo $zip->getFromName($src);
    $zip->close();
} else if($exec == 'delfile'){
    if($zip->deleteName($src)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'downloadfile'){
    /*header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$src);
    header('Content-Length: ' . filesize($src));
    readfile($src);*/
} else{
    echo "<script>location.href='index.php'</script>";
}

If you have questions please ask the question menu, please download the source code on how to create a zip archive file with php below.

Create Zip Archive File With PHP

Tags: , ,