Ian Ellis
Ian Ellis

Reputation: 99

PHP ZipArchive download working but not adding files to zip

I know there is many questions regarding the ZipArchive and how it works but after following all these I still can't get my program to work.

I don't know where i'm going wrong because I have die methods in and none of them are getting activated.

$path = "/export/scripts/CLOUD/logs/web/Private_Testbox/Jan_28_2013_16_20_44_atvts78_rollout_config/";

$fileName = explode('/', $path);
$zipname = $fileName[count($fileName) - 2];

$zip = new ZipArchive;
$handle = opendir($path);

//Check whether Zip can be opened
if ($zip->open($zipname, ZIPARCHIVE::CREATE) !== TRUE) {
    die("Could not open archive");
}

//Add all files to an array
while ($file = readdir($handle)) 
{
    $zip->addFile($path, $file);
}

closedir($handle);
$zip->close();

//Send zip folder 
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=' . $zipname . '.zip');
readfile($zip);

This file downloads the zip folder but there is never anything in it.

Thanks for help in advance.

Upvotes: 2

Views: 3067

Answers (1)

Marc B
Marc B

Reputation: 360922

You forgot a die() on the ->addFile() call, which means you're assuming that the files actually got added.

readfile() does not return the full path to a file in a directory, only the actual "local" filename, which means you're adding files which don't exist in the script's current working directory. Try:

$zip->addFile($file, $path . $file);
              ^^^^^^^^^^^^^^^^^^^^^

instead. As it stands now, your code is using $path as the filename to embed in the zip, and directories cannot be used as filenames. And without the $path . $file, addFile is looking in the wrong spot, e.g. it's the equivalent of getcwd() . $file instead.

Upvotes: 1

Related Questions