alex
alex

Reputation: 81

PHP Zip File Empty?

I have a script that creates a zip files from files in a certain directory. After Download, for a lot of users - the zip file is empty. However, for other users - the file isn't empty. Is it something I'm doing wrong?

header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$id.'.zip"');
header('Cache-Control: private');
ob_clean();
flush();
readfile("".$id.".zip");
exit;

Upvotes: 3

Views: 2241

Answers (2)

Brandon Horsley
Brandon Horsley

Reputation: 8104

I recommended this as a suggestion earlier, here is a skeleton of what I am talking about. It is untested as I don't have access to php at the moment.

$filename = $id . '.zip';
$handle = fopen($filename, 'r');
if ($handle === false)
{
    die('Could not read file "' . $filename . '"');
}

header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Cache-Control: private');
while (!feof($handle))
{
    echo fread($handle, 8192);
}
fclose($handle);
exit;

Upvotes: 0

hakre
hakre

Reputation: 197659

Better add some error control:

$file = "{$id}.zip";
if (!is_readable($file))
{
    die('Not accessible.');
}
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$file.'"');
header('Cache-Control: private');
ob_clean();
flush();
readfile($file);
exit;

Additionally triple check your output buffering configuration vs. readfile.

Upvotes: 1

Related Questions