Joe Almore Joe Almore - 3 months ago 7
PHP Question

PHP Downloads Some Empty Files and Some Normally

I have this code to download a Zip file from the server:

<?php
$path_parts = pathinfo($_GET['a']);
$file_name = $path_parts['basename'];
$file_path = 'temp/' . $file_name;

if (file_exists($file_path)) {
$size = filesize($file_path);

header('Cache-Control: must-revalidate');
header('Pragma: public');
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file_name");
header('Expires: 0');
header("Content-Type: application/zip");
header("Content-length: $size");
header("Content-Transfer-Encoding: binary");

// read the file from disk
readfile($file_path);
}

else
echo 'File does not exists';
?>


The files are stored in a
/temp
folder and the curious thing is that if I download a
TXT
file, it downlads OK, but if the file is a
ZIP
file then it downloads an empty file. Even if I change the extension of the
ZIP
file to
TXT
it still downloads empty, but any other file download just fine. What could be causing this behavior?

In fact, it downloads any other file but the
ZIP
files in the folder.

Answer

The problem is that PHP is not reading the ZIP files generated by the Java App that produces them. But, any other ZIP file is being read.

As I am using Java to create the ZIP files, I had to replace the method by this one posted here (https://www.mkyong.com/java/how-to-compress-files-in-zip-format/). It now works normally.

Comments