Create ZIP format and download whole folder or file using php | 2my4edge

14 January 2016

Create ZIP format and download whole folder or file using php

Here we are going to create or make zip file using php, by using php we can make .zip format, here we are going make whole folder or particular file as in zip format. let me show the php code.

ZIP format whole folder or file and download
DOWNLOAD                           LIVE DEMO

MAKE ZIP FORMAT OF WHOLE FOLDER
<?php
$dir = 'images'; //folder path

$archive = time().'download.zip';

$zip = new ZipArchive;
$zip->open($archive, ZipArchive::CREATE);
$files = scandir($dir);
unset($files[0], $files[1]);
foreach ($files as $file) {
$zip->addFile($dir.'/'.$file);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>

MAKE ZIP FORMAT FOR PARTICULAR FILE
<?php
$dir = 'index.php'; //direct file path

$archive = time().'download.zip';

$zip = new ZipArchive;
$zip->open($archive, ZipArchive::CREATE);


$zip->addFile($dir);


$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>

I hope this code is really helpful all developers, if you have any comments. comment below.






RELATED POSTS :

5 comments:

  1. Hi and thx for your code.

    to scan a Directory is the DirectoryIterator the better way. You have splittet filenames and dotted files have a isDot() member per File, scan is faster, but u must do every manually.

    for remove first both dotted dirs is unlink[0] / unlink[1] a realy bad way. better is here you check if the file has a prefix '.'.

    you can do that with preg_match('/^\./', $file) or with '.' == substr(0, 1, $file).

    file[0] and file[1] matches to . and .. but is realy luck in advance ... and a bad way to.

    ReplyDelete
  2. hello

    how to zip video folder .

    For video folder it is not working .

    but i am trying to zip for image folder then it is working properly so can you please suggest me how can i zip my video folder like image folder.

    Thanks in advance.

    ReplyDelete
  3. hi,
    bt i want to create zip in perticular directory.plz help

    ReplyDelete
  4. hi,
    i am many time try download zip file.but not complete my task..but please help me.

    ReplyDelete
    Replies
    1. Hello pooja

      just put the zip file link in anchor tag with download attribute by doing this you can download your zip file.

      Thanks

      Delete

^