ZIP all files in directory and download generated .zip

后端 未结 6 1597
逝去的感伤
逝去的感伤 2020-12-04 18:12

Well, first of all, this is my folder structure:

images/

image1.png
image11.png
image111.png
image223.png
generate_zip.php

And this is min

6条回答
  •  庸人自扰
    2020-12-04 18:22

    open('sample.zip',  ZipArchive::CREATE);
    $srcDir = "C:\\xampp\\htdocs\\uploads"; //location of the directory
    $files= scandir($srcDir);
    print_r($files);  // to check if files are actually coming in the array
    
    unset($files[0],$files[1]);
    foreach ($files as $file) {
        $zip->addFile($srcDir.'\\'.$file, $file);
        echo "bhandari";
    }
    $zip->close();
    
    $file='sample.zip';
    if (headers_sent()) {
        echo 'HTTP header already sent';
    } else {
        if (!is_file($file)) {
            header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
            echo 'File not found';
        } else if (!is_readable($file)) {
            header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
            echo 'File not readable';
        } else {
            header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: Binary");
            header("Content-Length: ".filesize($file));
            header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
            while (ob_get_level()) {
                ob_end_clean();
              }
            readfile($file);
            exit;
        }
    }
    
    
    
    ?>`enter code here`
    

    Note: Don't forget to use ob_start(); and end .

提交回复
热议问题