1

Used this code to make and download the zip, everything is working fine but the zip is downloading on web server's root. I want to download it from web to local machine.

    <?php

$dir = 'uploads/';
$bannerName =  $_POST['bName'];
$zip_file = $bannerName.'.zip';

// Get real path for our folder
$rootPath = realpath($dir);

// Initialize archive object
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

$htmlContent = $_POST['htmlData'];
$createIndex = "index.html";

$zip->addFromString("index.html", $htmlContent);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);
        $dirN = "assets/";
        // Add current file to archive
        $zip->addFile($filePath, $dirN.$relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);
?>

Whenever user clicks download button, it should start a download of the created zip, currently it's saving the zip on server's root.

Kunal Virk
  • 132
  • 5
  • Please provide complete path for download location. – Anshul Mar 07 '17 at 10:48
  • use `getcwd();` to get the current working directory. So you could append `uploads/` to the value returned by `getcwd()`. – Arun Mar 07 '17 at 10:50
  • @Arun I don't want to save those generated zips to my server...because getcwd() will help in retrieving saved zip on servers. – Kunal Virk Mar 07 '17 at 12:47
  • Did you try this ? [1](http://stackoverflow.com/questions/4165289/create-a-zip-file-using-php-class-ziparchive-without-writing-the-file-to-disk) or [2](http://stackoverflow.com/a/9648562/3126771) – Arun Mar 07 '17 at 12:56
  • @Arun i've tried these both the ways but i wonder if i'm making any mistake or what but unfortunately it not working – Kunal Virk Mar 07 '17 at 13:44

0 Answers0